codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
▲

Next.js

8 / 73 topics
8API Routes9Serverless Functions
Tutorials/Next.js/API Routes
▲Next.js

API Routes

Updated 2026-04-20
3 min read

API Routes

API routes are a powerful feature in Next.js that allow you to create server-side endpoints directly within your application without needing to set up an external backend. This makes it easy to build full-stack applications with Next.js, where the frontend and backend logic can be handled by the same codebase.

Introduction to API Routes

In traditional web development, APIs are often created using separate frameworks like Express or Koa. However, Next.js provides a built-in way to handle API requests directly within your application, which simplifies deployment and maintenance.

API routes in Next.js are defined inside the pages/api directory. Each file in this directory becomes an endpoint that can be accessed via HTTP requests. For example, creating a file named hello.js in the pages/api directory will create an API route at /api/hello.

Setting Up Your First API Route

Let's start by setting up a simple API route.

  1. Create the API Route File

    Inside your Next.js project, create the following directory structure if it doesn't already exist:

    my-next-app/
    └── pages/
        └── api/
            └── hello.js
    
  2. Write the API Route Handler

    Open hello.js and add the following code:

    // pages/api/hello.js
    
    export default function handler(req, res) {
      res.status(200).json({ message: 'Hello from Next.js!' });
    }
    
  3. Test the API Route

    Start your Next.js development server by running npm run dev or yarn dev. Once the server is running, open your browser and navigate to http://localhost:3000/api/hello. You should see a JSON response with the message "Hello from Next.js!".

Understanding the Request and Response Objects

The API route handler function receives two arguments: req (the request object) and res (the response object). These objects are similar to those used in Express or other Node.js frameworks.

Request Object (req)

  • req.method: The HTTP method of the request (e.g., GET, POST).
  • req.query: An object containing query parameters.
  • req.body: An object containing the body of the request. This is available only for POST, PUT, and PATCH requests.

Response Object (res)

  • res.status(code): Sets the HTTP status code for the response.
  • res.json(body): Sends a JSON response.
  • res.send(body): Sends a plain text or HTML response.
  • res.redirect(url): Redirects to another URL.

Handling Different HTTP Methods

API routes can handle multiple HTTP methods. Here's an example of how to handle GET and POST requests:

// pages/api/user.js

export default function handler(req, res) {
  if (req.method === 'GET') {
    // Handle GET request
    res.status(200).json({ message: 'Fetching user data' });
  } else if (req.method === 'POST') {
    // Handle POST request
    const userData = req.body;
    res.status(201).json({ message: 'User created', data: userData });
  } else {
    // Handle other methods
    res.setHeader('Allow', ['GET', 'POST']);
    res.status(405).end(`Method ${req.method} Not Allowed`);
  }
}

Accessing Environment Variables

API routes can access environment variables just like any other part of your Next.js application. You can define environment variables in a .env.local file at the root of your project.

// .env.local

API_KEY=your_api_key_here

You can then access this variable inside your API route handler:

// pages/api/secure.js

export default function handler(req, res) {
  const apiKey = process.env.API_KEY;
  if (apiKey === req.headers['x-api-key']) {
    res.status(200).json({ message: 'Access granted' });
  } else {
    res.status(401).json({ message: 'Unauthorized' });
  }
}

Best Practices for API Routes

  1. Keep Logic Minimal: API routes should handle only the necessary logic. Complex business logic should be moved to separate modules or services.

  2. Error Handling: Always include error handling in your API routes to provide meaningful responses in case of errors.

  3. Security: Validate and sanitize all inputs to prevent security vulnerabilities like SQL injection, XSS, etc.

  4. Rate Limiting: Implement rate limiting to protect your API from abuse.

  5. Caching: Use caching strategies to improve performance for frequently accessed data.

Advanced Features

Dynamic API Routes

Next.js supports dynamic API routes using square brackets in the file name. For example, pages/api/user/[id].js will create an API route that matches /api/user/1, /api/user/2, etc.

// pages/api/user/[id].js

export default function handler(req, res) {
  const userId = req.query.id;
  // Fetch user data based on the ID
  res.status(200).json({ message: `Fetching user with ID ${userId}` });
}

API Routes with Middleware

You can use Next.js middleware to execute code before your API routes. This is useful for tasks like authentication, logging, or modifying requests.

// pages/api/_middleware.js

export function middleware(req, ev) {
  if (!req.headers.authorization) {
    return Response.redirect('/api/auth');
  }
  return NextResponse.next();
}

Serverless Functions

API routes in Next.js are serverless functions. This means they are automatically scaled and managed by Vercel or other hosting providers. Each function is isolated and runs independently, which can improve performance and reliability.

Conclusion

API routes in Next.js provide a powerful and flexible way to create server-side endpoints directly within your application. By following best practices and leveraging advanced features like dynamic routes and middleware, you can build robust and efficient APIs that integrate seamlessly with your frontend components.


PreviousCatch All RoutesNext Serverless Functions

Recommended Gear

Catch All RoutesServerless Functions