Next.js simplifies the process of building API routes by allowing you to create serverless functions directly within your app. These routes can handle various types of server-side logic, such as fetching data, processing forms, or integrating with third-party APIs. Here's how to create your first API route in Next.js.
What Are API Routes in Next.js?
API routes in Next.js enable you to define backend endpoints as part of your Next.js application. These routes are serverless functions that run on demand, and they can be deployed alongside your frontend code.
Key Features of API Routes:
Ease of Use: API routes are simple to set up and live within your Next.js project.
Serverless: Each route is deployed as a serverless function.
Flexible: They can handle requests like GET, POST, PUT, DELETE, etc.
Setting Up Your First API Route
Step 1: Create the api
Folder
In your project directory, navigate to the src/app
folder (if you're using the src
directory setup) or the app
folder. Inside, create a folder named api
.
src/app/api/
Step 2: Define an API Route
Inside the api
folder, create a file named hello.ts
. This file will define a simple API endpoint.
// src/app/api/hello.ts
import { NextApiRequest, NextApiResponse } from 'next';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json({ message: 'Hello, world!' });
}
Step 3: Access the API Route
Start your development server with:
npm run dev
Open your browser and navigate to http://localhost:3000/api/hello
. You should see the following JSON response:
{
"message": "Hello, world!"
}
Handling Different HTTP Methods
API routes in Next.js can handle multiple HTTP methods. Here’s how you can differentiate between them:
// src/app/api/greet.ts
import { NextApiRequest, NextApiResponse } from 'next';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === 'GET') {
res.status(200).json({ message: 'This is a GET request' });
} else if (req.method === 'POST') {
const { name } = req.body;
res.status(200).json({ message: `Hello, ${name}!` });
} else {
res.setHeader('Allow', ['GET', 'POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
Testing the API
GET Request: Access
http://localhost:3000/api/greet
in your browser.POST Request: Use a tool like Postman or cURL to send a POST request with a JSON body:
{
"name": "John Doe"
}
Response:
{
"message": "Hello, John Doe!"
}
Adding Query Parameters
You can access query parameters from the request object using req.query
:
// src/app/api/user.ts
import { NextApiRequest, NextApiResponse } from 'next';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
const { id } = req.query;
res.status(200).json({ message: `User ID is ${id}` });
}
Access the API route with a query parameter, e.g., http://localhost:3000/api/user?id=123
, and you’ll get:
{
"message": "User ID is 123"
}
Deploying API Routes
When you deploy your Next.js application, API routes are automatically deployed as serverless functions. Popular platforms like Vercel and Netlify support this out of the box.
Use Cases for API Routes
Form Submission: Handle user input securely.
Data Fetching: Integrate with third-party APIs or databases.
Authentication: Validate user credentials and manage sessions.
Dynamic Content: Generate personalized or real-time responses.
Conclusion
Creating API routes in Next.js is straightforward and powerful. They allow you to add backend functionality without the need for a separate server. By following the steps above, you can build flexible and scalable API endpoints directly within your Next.js app. Start exploring the possibilities and enhance your applications with serverless API routes!