Learn how to integrate Now.js with Node.js and Express backend
This example demonstrates how to create a full-stack application using Now.js for the frontend and Node.js/Express for the backend. We'll build a simple user management system with CRUD operations.
mkdir now-node-example
cd now-node-example
npm init -y
npm install express cors mongoose dotenv
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>User Management - Now.js</title>
<link rel="stylesheet" href="/css/base.css">
<script src="/js/Now.js"></script>
</head>
<body>
<div id="app"></div>
</body>
</html>
// server.js
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
// Middleware
app.use(cors());
app.use(express.json());
// MongoDB Connection
mongoose.connect(process.env.MONGODB_URI);
// User Model
const User = mongoose.model('User', {
name: String,
email: String,
role: String
});
// Routes
app.get('/api/users', async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.post('/api/users', async (req, res) => {
try {
const user = new User(req.body);
await user.save();
res.status(201).json(user);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
// UserManager Component
Now.getManager('component').define('user-manager', {
template: `
User Management
Name
Email
Role
Actions
{{#each users}}
{{name}}
{{email}}
{{role}}
{{/each}}
`,
state: {
users: [],
form: {
name: '',
email: '',
role: 'user'
}
},
async created() {
await this.loadUsers();
},
methods: {
async loadUsers() {
try {
const response = await fetch('http://localhost:3000/api/users');
this.state.users = await response.json();
} catch (error) {
console.error('Failed to load users:', error);
}
},
async handleSubmit(event) {
event.preventDefault();
try {
const response = await fetch('http://localhost:3000/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(this.state.form)
});
const user = await response.json();
this.state.users.push(user);
// Reset form
this.state.form = {
name: '',
email: '',
role: 'user'
};
} catch (error) {
console.error('Failed to add user:', error);
}
}
}
});
// Initialize Now.js
await Now.init({
app: {
name: 'User Management',
version: '1.0.0'
}
});
// Create app instance
const app = await Now.createApp();
// Mount to DOM
await app.mount('#app');
node server.js
# Using any static file server
npx serve .