If you want to put the entire frontend in a single Next.js page, you can combine the “users list,” “add/edit form,” and all CRUD logic in one page.jsx file. Since you’re using Next.js 13+ with the App Router, this would go under:
app/users/page.jsx
I’ll explain step by step and then give a full single-page working example.
1 ️⃣ Key idea
Everything is in one component (UsersPage).
State variables: users, name, email, editingUser.
CRUD functions: fetchUsers, handleSubmit (add/update), handleEdit, handleDelete.
Axios calls Next.js API routes (/api/users and /api/users/:id).
2 ️⃣ Full single-page frontend code
'use client';
import { useState, useEffect } from 'react';
import axios from 'axios';
export default function UsersPage() {
const [users, setUsers] = useState([]);
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [editingUser, setEditingUser] = useState(null);
// Fetch all users
const fetchUsers = async () => {
try {
const res = await axios.get('/api/users');
setUsers(res.data);
} catch (error) {
console.error('Failed to fetch users', error);
}
};
useEffect(() => {
fetchUsers();
}, []);
// Add or update user
const handleSubmit = async (e) => {
e.preventDefault();
try {
if (editingUser) {
await axios.put(`/api/users/${editingUser._id}`, { name, email });
setEditingUser(null);
} else {
await axios.post('/api/users', { name, email });
}
setName('');
setEmail('');
fetchUsers();
} catch (error) {
console.error('Failed to save user', error);
}
};
// Edit user
const handleEdit = (user) => {
setEditingUser(user);
setName(user.name);
setEmail(user.email);
};
// Delete user
const handleDelete = async (id) => {
try {
await axios.delete(`/api/users/${id}`);
fetchUsers();
} catch (error) {
console.error('Failed to delete user', error);
}
};
return (
User Management
{/* Add/Edit Form */}
{/* Users Table */}
| ID |
Name |
Email |
Actions |
{users.length > 0 ? (
users.map((user) => (
| {user._id} |
{user.name} |
{user.email} |
|
))
) : (
|
No users found
|
)}
);
}
==================backend for this frontend=========
1 ️⃣ Install dependencies
npm install express cors mongoose
2 ️⃣ server.js with MongoDB
import express from 'express';
import cors from 'cors';
import mongoose from 'mongoose';
const app = express();
const PORT = 5000;
// MongoDB connection
const MONGO_URI = 'mongodb://127.0.0.1:27017/usersdb'; // replace with your URI
mongoose.connect(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('MongoDB connected'))
.catch((err) => console.error('MongoDB connection error:', err));
// Define User schema
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
}, { timestamps: true });
const User = mongoose.model('User', userSchema);
// Middleware
app.use(cors());
app.use(express.json());
// GET all users
app.get('/api/users', async (req, res) => {
try {
const users = await User.find().sort({ createdAt: -1 });
res.json(users);
} catch (err) {
res.status(500).json({ error: 'Failed to fetch users' });
}
});
// POST new user
app.post('/api/users', async (req, res) => {
try {
const newUser = new User(req.body);
const savedUser = await newUser.save();
res.status(201).json(savedUser);
} catch (err) {
res.status(500).json({ error: err.message || 'Failed to create user' });
}
});
// PUT update user
app.put('/api/users/:id', async (req, res) => {
try {
const updatedUser = await User.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true, runValidators: true }
);
if (!updatedUser) return res.status(404).json({ error: 'User not found' });
res.json(updatedUser);
} catch (err) {
res.status(500).json({ error: err.message || 'Failed to update user' });
}
});
// DELETE user
app.delete('/api/users/:id', async (req, res) => {
try {
const deletedUser = await User.findByIdAndDelete(req.params.id);
if (!deletedUser) return res.status(404).json({ error: 'User not found' });
res.json(deletedUser);
} catch (err) {
res.status(500).json({ error: err.message || 'Failed to delete user' });
}
});
app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));