This tutorial shows how to build a fully functional CRUD app using Node.js for the backend and htmx for the frontend. This demonstrates htmx's integration into a full-stack application, helping you evaluate its suitability for your projects.
htmx is a JavaScript library enhancing web apps with partial HTML updates, eliminating full-page reloads. It transmits HTML directly, unlike the JSON payloads of traditional frameworks.
Key Features:
HX-Request
header.Application Overview:
The tutorial builds a simple contact manager supporting CRUD operations. htmx provides an SPA-like experience, enhancing user interaction. JavaScript-disabled browsers still function correctly with full-page refreshes, ensuring accessibility and SEO.
Project Setup:
This requires Node.js. Verify installation with node -v
and npm -v
. Create the project:
mkdir contact-manager cd contact-manager npm init -y npm i express method-override pug
Create app.js
:
const express = require('express'); const path = require('path'); const routes = require('./routes/index'); const methodOverride = require('method-override'); const app = express(); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug'); app.use(express.urlencoded({ extended: true })); app.use(methodOverride('_method')); app.use(express.static('public')); app.use('/', routes); const server = app.listen(3000, () => { console.log(`Express is running on port ${server.address().port}`); });
Create routes/index.js
(initial content omitted for brevity, see GitHub repo). Add "scripts": { "dev": "node --watch app.js" }
to package.json
. Run npm run dev
.
The tutorial then details creating the views (Pug templates), styling (CSS), and implementing the htmx features for displaying contacts, creating new contacts, editing, and deleting contacts, all while handling full page refreshes and providing user feedback. The complete code is available on the accompanying GitHub repository. The tutorial concludes with suggestions for extending the application.
The above is the detailed content of Build a Full-stack App with Node.js and htmx. For more information, please follow other related articles on the PHP Chinese website!