API Routes in Next.js: Building Serverless Functions

@rnab
3 min readFeb 16, 2025

--

As the lines between frontend and backend development continue to blur, frameworks like Next.js provide an all-in-one solution to create full-fledged applications with ease. One of Next.js’s standout features is its ability to handle server-side logic using API Routes. These serverless functions allow developers to create fully functional APIs directly within their Next.js applications. In this article, we’ll explore how to build and use API Routes in Next.js with TypeScript for a more maintainable codebase.

What Are API Routes?

API Routes in Next.js allow you to define endpoint functions that handle HTTP requests within your application. They work seamlessly with serverless infrastructure, perfect for building RESTful APIs, handling form submissions, authenticating requests, and much more. Since these routes are executed on the server side, they can securely interact with your database and other external services without exposing any sensitive data to the client.

Setting Up a Next.js Project with TypeScript

Before we dive into building API routes, let’s ensure we have a Next.js project set up with TypeScript. If you haven’t already, you can create a new Next.js app with TypeScript using the following command:

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

This command will create a new Next.js project named ‘my-nextjs-app’ using TypeScript.

Creating an API Route

Next.js allows you to create API routes by adding TypeScript files (*.ts) under the pages/api directory. Each file represents a distinct API endpoint. Let's create a simple API route to fetch user data.

  1. Navigate to the /pages/api directory. If it doesn't exist, you can create it.
  2. Create a new file named users.ts.

Here’s an example of a basic API route defined in users.ts:

import { NextApiRequest, NextApiResponse } from 'next';

type User = {
id: number;
name: string;
email: string;
};

// Mock data - In a real-world scenario, you'd fetch this data from a database.
const users: User[] = [
{ id: 1, name: 'Alice Smith', email: 'alice@example.com' },
{ id: 2, name: 'Bob Johnson', email: 'bob@example.com' },
];

export default function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === 'GET') {
res.status(200).json(users);
} else {
res.setHeader('Allow', ['GET']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}

Breaking Down the API Route Code

  • Imports: We import NextApiRequest and NextApiResponse from Next.js, which are types that provide auto-completion and error-checking for request and response objects.
  • Data Type Definition: Define a User type for better TypeScript support and maintainability.
  • Mock Data: We use an array of mock user data. In a real application, you would fetch this data from a database or an external API.
  • Handler Function: This function responds to incoming HTTP requests. We’re checking if the request is a GET request and then responding with the user data. Otherwise, it returns a 405 Method Not Allowed error.

Consuming the API Route

Your API endpoint can be consumed like any other RESTful API. Here’s how you can call this endpoint from your client-side code:

async function fetchUsers() {
const response = await fetch('/api/users');
const users = await response.json();
console.log(users);
}

fetchUsers();

Deployment and Environment Considerations

Next.js API Routes run as serverless functions, which means they’re executed on-demand and scale automatically. When deploying to platforms like Vercel, these routes automatically become serverless functions.

However, if you’re dealing with sensitive data or require third-party API keys, ensure those are managed via environment variables. Next.js supports .env.local files for local development environment variables.

Conclusion

API Routes in Next.js provide a powerful and scalable way to handle backend logic within your application. By leveraging TypeScript, you ensure that your code is not only robust but also easier to read and maintain. Whether you’re creating a simple contact form handler or a complex data processing task, API Routes provide the flexibility you need without additional infrastructure overhead. Happy coding! 🚀

Would you like to see more advanced examples, or is there a specific use-case you are curious about? Share your thoughts!

--

--

@rnab
@rnab

Written by @rnab

Typescript, Devops, Kubernetes, AWS, AI/ML, Algo Trading

No responses yet