Back to articles

Mastering Serverless Functions with Next.js API Routes

AuthorMajd Muhtaseb04/28/20257 minutes
Mastering Serverless Functions with Next.js API Routes

Next.js API routes provide an elegant way to build serverless functions directly within your React applications. This eliminates the need for separate backend infrastructure for many common tasks, making your application more performant and scalable.

What are Next.js API Routes?

API Routes are functions defined in the pages/api directory of your Next.js project. When you deploy your Next.js application, these functions are automatically deployed as serverless functions (typically on AWS Lambda, Vercel Functions, or similar). They can handle HTTP requests (GET, POST, PUT, DELETE, etc.) and return responses.

Creating Your First API Route

  1. Create a file in pages/api, for example, pages/api/hello.js.
  2. Add the following code:
export default function handler(req, res) {
  res.status(200).json({ name: 'Hello, world!' })
}

This simple function responds with a JSON object containing the message "Hello, world!".

Handling Different HTTP Methods

You can handle different HTTP methods within the same API route using the req.method property.

export default function handler(req, res) {
  if (req.method === 'GET') {
    // Get data from your data source
    res.status(200).json({ message: 'Fetched data' });
  } else if (req.method === 'POST') {
    // Create or update data
    const body = req.body;
    res.status(201).json({ message: 'Data created', data: body });
  } else {
    res.status(405).json({ message: 'Method Not Allowed' });
  }
}

Reading Request Body and Query Parameters

To access data sent in the request body (e.g., from a POST request), use req.body. To access query parameters in the URL (e.g., /api/users?id=123), use req.query.

export default function handler(req, res) {
  const { id } = req.query;
  const data = req.body;

  console.log("Query Parameter ID:", id);
  console.log("Request Body:", data);

  res.status(200).json({ id, data });
}

Example: Fetching Data from an API

You can use API routes to fetch data from external APIs and expose it through your own API.

export default async function handler(req, res) {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    const data = await response.json();
    res.status(200).json(data);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Failed to fetch data' });
  }
}

Benefits of Using Next.js API Routes

  • Simplified Backend: Reduces the need for separate backend infrastructure.
  • Improved Performance: Serverless functions scale automatically.
  • Easy Deployment: Deploy directly with your Next.js application.
  • Full Stack Development: Develop frontend and backend logic in the same project.

Conclusion

Next.js API routes offer a powerful and convenient way to build serverless functions. They are ideal for tasks like handling form submissions, fetching data, processing payments, and more. By mastering API routes, you can create more efficient and scalable Next.js applications.