API Routes
Build complete APIs directly in Next.js
10-15 min
Next.js API Routes
Next.js API Routes let you create API endpoints directly inside your application, turning Next.js into a complete full-stack solution.
Introduction to API Routes
Core concept
API Routes are serverless functions that run on the server side. Each file in pages/api/ becomes an API endpoint.
pages/
└── api/
├── hello.js → /api/hello
├── users/
│ ├── index.js → /api/users
│ └── [id].js → /api/users/123
└── auth/
├── login.js → /api/auth/login
└── logout.js → /api/auth/logout
Your first endpoint
// pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({
message: 'Hello from Next.js API!',
timestamp: new Date().toISOString()
})
}
Test with curl:
curl http://localhost:3000/api/hello
Handling HTTP methods
Multi-method endpoint
// pages/api/users/index.js
export default function handler(req, res) {
const { method } = req
switch (method) {
case 'GET':
return getUsers(req, res)
case 'POST':
return createUser(req, res)
default:
res.setHeader('Allow', ['GET', 'POST'])
res.status(405).end(`Method ${method} Not Allowed`)
}
}
async function getUsers(req, res) {
try {
// Fetch users from the database
const users = await db.user.findMany()
res.status(200).json(users)
} catch (error) {
res.status(500).json({ error: 'Erreur serveur' })
}
}
async function createUser(req, res) {
try {
const { name, email } = req.body
// Validation
if (!name || !email) {
return res.status(400).json({
error: 'Nom et email requis'
})
}
// Create the user
const user = await db.user.create({
data: { name, email }
})
res.status(201).json(user)
} catch (error) {
res.status(500).json({ error: 'Erreur lors de la création' })
}
}
Comments
Comments are powered by GitHub Discussions
Sign in with GitHub to join the discussion