How to Use Next.js API Routes: Practical Tutorial
Next.js API routes allow you to build backend functionality directly in a Next.js application without needing a separate server. These routes are serverless functions that run on-demand, offering a simple way to handle tasks like fetching data, processing forms, authenticating users, and more.
Prerequisites
- Basic knowledge of JavaScript and React
- Node.js installed on your computer
- Next.js project setup (if you need guidance, see our How to Install Next.js: Beginner’s Step-by-Step Guide)
- Familiarity with API concepts
What Are Next.js API Routes?
API routes in Next.js let you create backend endpoints as files inside the pages/api directory. Each file automatically maps to an API endpoint. These routes run server-side code when called, enabling you to respond with JSON, perform CRUD operations, or integrate with external services.
Creating Your First API Route
- Create a file: Inside your Next.js project directory, navigate to
pages/apiand create a file calledhello.js. - Add the handler function: This function receives
req(request) andres(response) objects. Write a simple response like this:
export default function handler(req, res) {
res.status(200).json({ message: 'Hello from Next.js API route!' });
}
This defines a GET endpoint at /api/hello.
How to Call API Routes from the Frontend
You can use fetch or any HTTP client to call the API. For example, inside a React component:
import { useEffect, useState } from 'react';
export default function HelloComponent() {
const [message, setMessage] = useState('');
useEffect(() => {
fetch('/api/hello')
.then(res => res.json())
.then(data => setMessage(data.message));
}, []);
return <div>{message}</div>;
}
This fetches and displays the message from our API route.
Example: A Simple Todo API
Let’s build a basic todo API with GET and POST methods to manage todo items in memory.
let todos = [];
export default function handler(req, res) {
if (req.method === 'GET') {
res.status(200).json(todos);
} else if (req.method === 'POST') {
const todo = req.body.todo;
if (!todo) {
return res.status(400).json({ error: 'Todo content missing' });
}
todos.push(todo);
res.status(201).json({ message: 'Todo added', todos });
} else {
res.setHeader('Allow', ['GET', 'POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
This example accepts GET requests to list todos, and POST requests to add a todo.
Tips for Handling API Routes
- Use middleware: Next.js API routes support middleware for authentication, logging, etc.
- Secure your routes: Validate user input and protect sensitive endpoints.
- Keep it stateless: Since routes can be serverless, avoid relying on in-memory states in production; use databases or external storage.
- Handle CORS if needed: If your frontend differs from your backend domain, configure CORS headers carefully.
Troubleshooting Common Issues
- API route returns 404: Make sure the file is inside
pages/apiand exported properly. - Method Not Allowed errors: Verify your handler supports your HTTP methods.
- JSON parsing errors: Use
req.bodyafter parsing middleware or check your request headers. - Slow responses: Check external API calls or database queries and optimize them.
Summary Checklist
- Create API routes in
pages/apifolder - Export default handler function with
req,res - Use HTTP method checks (GET, POST, etc.) for different request types
- Call API routes with fetch() or other HTTP clients from frontend
- Test routes with tools like Postman or curl
- Secure and validate inputs for production readiness
For more on working with Next.js, check out our How to Create Pages in Next.js: Step-by-Step Tutorial to complement your API knowledge.
