Next.js API Routes Building Server-Side Functionality
Blog Owner
2 min read
329 words

The pages/api/users.js file defines an API route accessible at /api/users.
The handler function accepts two parameters: req (a NextApiRequest object representing the HTTP request) and res (a NextApiResponse object for the HTTP response).
For GET requests, it returns a user list (hardcoded here, but typically queried from a database in practice).
For POST requests, it accepts user data from the request body, simulates adding it to a database, and returns a success message.
For unsupported methods, it returns a 405 Method Not Allowed error with allowed methods specified.
Next.js API Routes enable the creation of standalone server-side functionality within a Next.js application, capable of handling HTTP requests and returning JSON data or other responses. API routes reside in the pages/api directory, with each file mapping to a specific API endpoint.
Basic Example
pages/api/users.js
import type { NextApiRequest, NextApiResponse } from 'next';
// Get user list
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === 'GET') {
const users = [
{ id: 1, name: 'User 1' },
{ id: 2, name: 'User 2' },
{ id: 3, name: 'User 3' },
];
res.status(200).json(users);
} else if (req.method === 'POST') {
const user = req.body;
// Simulate database connection
// await addUserToDatabase(user);
res.status(201).json({ message: 'User added successfully.' });
} else {
res.setHeader('Allow', ['GET', 'POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}- The pages/api/users.js file defines an API route accessible at /api/users.
- The handler function accepts two parameters: req (a NextApiRequest object representing the HTTP request) and res (a NextApiResponse object for the HTTP response).
- For GET requests, it returns a user list (hardcoded here, but typically queried from a database in practice).
- For POST requests, it accepts user data from the request body, simulates adding it to a database, and returns a success message.
- For unsupported methods, it returns a 405 Method Not Allowed error with allowed methods specified.
Next.js API Routes handle JSON responses by default, but you can return other content types as needed. For example, use res.send to return HTML.


