Back to articles

Mastering Serverless Functions with Next.js API Routes

AuthorMajd Muhtaseb07/12/20257 minutes
Mastering Serverless Functions with Next.js API Routes

Introduction

Next.js API Routes provide an incredibly easy way to create serverless functions directly within your Next.js application. These functions execute on the edge, offering scalability, cost-effectiveness, and improved performance. This article will guide you through the process of creating and deploying serverless functions using Next.js API Routes.

Setting Up Your Next.js Project

If you don't already have a Next.js project, create one:

npx create-next-app@latest my-nextjs-app
cd my-nextjs-app

Creating Your First API Route

API routes are located in the pages/api directory. Let's create a simple API route that returns a JSON response.

Create a file named pages/api/hello.js with the following content:

export default function handler(req, res) {
  res.status(200).json({ name: 'John Doe' });
}

This function takes two arguments:

  • req: An instance of http.IncomingMessage, plus some pre-built middlewares.
  • res: An instance of http.ServerResponse, plus some helper functions.

Testing Your API Route

Start your Next.js development server:

npm run dev

Now, visit http://localhost:3000/api/hello in your browser. You should see the JSON response:

{
  "name": "John Doe"
}

Handling Different HTTP Methods

You can handle different HTTP methods (GET, POST, PUT, DELETE, etc.) within your API route:

export default function handler(req, res) {
  if (req.method === 'GET') {
    res.status(200).json({ message: 'This is a GET request' });
  } else if (req.method === 'POST') {
    const body = req.body;
    res.status(200).json({ message: 'This is a POST request', data: body });
  } else {
    res.status(405).json({ message: 'Method Not Allowed' });
  }
}

To test the POST request, you can use curl:

curl -X POST -H "Content-Type: application/json" -d '{"name": "Jane Doe"}' http://localhost:3000/api/hello

Reading Request Body

As shown in the POST example above, you can access the request body using req.body. Next.js automatically parses JSON bodies. For other content types, you may need to use a middleware like body-parser which could create conflicts, so using JSON is advisable.

Deploying Your API Routes

When you deploy your Next.js application to platforms like Vercel or Netlify, the API routes are automatically deployed as serverless functions. No extra configuration is typically needed.

Example: Fetching Data from an 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' });
  }
}

Conclusion

Next.js API Routes simplify the process of building serverless functions. They offer a clean and efficient way to handle backend logic within your Next.js applications, enabling you to build scalable and performant web applications with ease. Experiment with different functionalities and explore the possibilities of serverless architecture within the Next.js ecosystem.