Table of contents
1.
Introduction
2.
API Routes in Next.js
2.1.
Implementation Details
3.
Dynamic API Routes in Next.js
3.1.
API Structure
3.2.
Catching All API Routes
4.
Response Helpers
4.1.
Status Code of Response
4.2.
Sending Response in JSON Format
4.3.
Sending Response in HTTP Format
4.4.
Redirects to a specified path or URL
5.
Frequently Asked Questions (FAQs)
6.
Key Takeaways
Last Updated: Mar 27, 2024

Writing Backend API Routes in Next.js

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Source: Link

Introduction

Next.js is a React framework that allows you to create single-page Javascript apps. This framework has various advantages for our clients' applications and our development team. 

As users, we get increasingly irritated as our expectations are not met by websites and apps that take longer than milliseconds to load. We've started utilizing Next.js for various reasons, the majority of which are linked to speed and performance. 

Technology decisions play a huge part in producing highly performant, scalable, and successful apps, and as such, we've started using them for a variety of reasons.

We'll learn about the API routes in next.js. We will also learn the concept of Dynamic API routes and API structure in Next.js. We will also see how to send a response in JSON and HTTP formats.

Let us dive deep into the concepts of environment variables in Next.js.

API Routes in Next.js

API routes provide us with a solution to build your API with Next.js.

Next.js API routes adhere to the REST (representational state transfer) protocol, a standardized protocol used by the majority of internet APIs. As such, we have a great amount of flexibility for designing the routes of the API.

This API will support two routes: one that accepts a slug and another that accepts a JSON object containing a query attribute.

  • Route of the slug: A slug is a unique identifier for a URL in web development, often found at the end of the URL. The slug in the URL https://example.com/blog/this-is-the-post is this-is-the-post, for example. The URL for this API will be something like this: http://localhost:3000/api/[slug], where [slug] is the desired query. It's termed a dynamic route since the URL of this route changes depending on the request. On sending a GET request directed to the server with the desired query URL will complete this API route.
  • This API route accepts a JSON object with the type "query": QUERY, where QUERY is the requested format. This API route cannot be accessed simply by changing the URL; it must be accessed using a POST request directed to the server, with the body of the request including the object in the format indicated.

All of these routes will be defined as lambda functions, with a req request argument (for interacting with the user's request) and a res response parameter (for interacting with the response data to send back to the user).

Any file in the pages/api subdirectory is mapped to /api/* and regarded as an API endpoint rather than a page. They're exclusively server-side bundles; therefore, they won't add to the size of your client-side bundle.

The following API route is used pages/api/user.js, for example, delivers a JSON response with a 200 success code:

export default function handler(req, res) {
 res.status(200).json({ name: 'Coding Ninjas' })
}
You can also try this code with Online Javascript Compiler
Run Code

 

To make an API route work, you must first export a default function (also known as a request handler), which will then receive the following parameters:

You may use req.method in your request handler to handle different HTTP methods in an API route, like this:

export default function handler(req, res) {
 if (req.method === 'POST') {
   // Process a POST request
 } else {
   // Handle any other HTTP method
 }
}
You can also try this code with Online Javascript Compiler
Run Code

Implementation Details

API Routes can be used to create a whole API for new projects. If you already have an API, you don't need to use an API Route to route calls to it. Other applications using API Routes include:

  • Masking an external service's URL (for example, using /api/secret instead than https://company.com/secret-url)
  • To safely access external services, use Environment Variables on the server.

Dynamic API Routes in Next.js

Dynamic routes are supported through API routes, which use the same file naming conventions as pages.

The code for the API route pages/api/post/[pid].js, for example, is as follows:

export default function handler(req, res) {
 const { pid } = req.query
 res.end(`Post: ${pid}`)
}
You can also try this code with Online Javascript Compiler
Run Code

A request for '/api/post/abc' now returns the text 'Post: abc.'

API Structure

Setting up routes like this is a standard RESTful pattern. 

'GET api/posts' returns a paginated list of entries; 'GET api/posts/2139' returns the post id 2139.

We can model this in two ways:

  • Option 1:
    • ‘/api/posts.js’
    • ‘/api/posts/[postId].js’
  • Option 2:
    • ‘/api/posts/index.js’
    • ‘/api/posts/[postId].js’

Both are the same. A third option is to just use /api/posts/[postId]. Because Dynamic Routes have no undefined state, GET api/posts will never match /api/posts/[postId]. js.

Catching All API Routes

By adding three dots (...) inside the brackets, API Routes can be expanded to catch all paths. 'pages/api/post/[...slug].js', for example, matches '/api/post/a' as well as '/api/post/a/x, /api/post/a/x/y,' and so on.

Note that we can use names other than 'slug,' for example: '[...param]'.

The following 'query' object will be provided to the page as a query parameter ('slug' in this example), and it will always be an array; thus, the path '/api/post/a' will contain the following 'query' object:

{ "slug": ["a"] }
You can also try this code with Online Javascript Compiler
Run Code

The new parameters added to the array in the case of '/api/post/a/y' and any other matching path, as follows:

{ "slug": ["a", "y"] }
You can also try this code with Online Javascript Compiler
Run Code

The following is an example of an API route for 'pages/api/post/[...slug].js':

export default function handler(req, res) {
 const { slug } = req.query
 res.end(`Post: ${slug.join(', ')}`)
}
You can also try this code with Online Javascript Compiler
Run Code


A request to '/api/post/a/x/y' now returns the following text: 'Post: a, x, y'.

Response Helpers

The Server Response object (commonly abbreviated as 'res') contains a set of Express.js-style helper methods to improve the experience of the developer and speed up the creation of new API endpoints.

The following people are included as helpers:

  • 'res.status(code)' - It sets the status code. 'code' must be an HTTP status code that is valid.
  • 'res.json(body)' - It returns a JSON object. The object 'body' must be serializable.
  • 'res.send(body)' is a function that sends the HTTP response. A'string,' a 'object,' or a 'Buffer' can be used as the 'body.'
  • 'res.redirect([status,] path)' - Redirects to a path or URL specified by the user. The value of 'status' must be an HTTP status code that is valid. 'status' defaults to "307" "Temporary redirect" if not given.

Status Code of Response

You can set the status code of a response when sending it back to the client.

The following example updates the response's status code to 200 (OK) and returns a JSON response with the message attribute set to 'Hello from CodingNinjas!':

export default function handler(req, res) {
 res.status(200).json({ message: 'Hello from CodingNInjas!' })
}
You can also try this code with Online Javascript Compiler
Run Code

Sending Response in JSON Format

You can send the client a JSON response, but it must be a serializable object. In a real-world application, based on the answer from the requested endpoint, you might want to inform the client about the request's status.

The example below sends a JSON response with the status code 200 (OK) and the async operation result. It's wrapped in a try-catch block to handle any issues that may arise, with the relevant status code and error message being caught and returned to the client:

export default async function handler(req, res) {
 try {
   const result = await someAsyncOperation()
   res.status(200).json({ result })
 } catch (err) {
   res.status(500).json({ error: 'failed to load data' })
 }
}
You can also try this code with Online Javascript Compiler
Run Code

Sending Response in HTTP Format

An HTTP response is sent in the same way that a JSON response is sent. The response body can be a string, an object, or a Buffer, with the main distinction being that it can be a string, an object, or a Buffer.

The example below delivers an HTTP response with the status code 200 (OK) and the async operation result.

export default async function handler(req, res) {
 try {
   const result = await someAsyncOperation()
   res.status(200).send({ result })
 } catch (err) {
   res.status(500).send({ error: 'failed to fetch data' })
 }
}
You can also try this code with Online Javascript Compiler
Run Code

Redirects to a specified path or URL

You could wish to redirect your client to a specific path or URL after they've submitted a form, for example.

If the form is successfully submitted, the following example redirects the client to the / path:

export default async function handler(req, res) {
 const { name, message } = req.body
 try {
   await handleFormInputAsync({ name, message })
   res.redirect(307, '/')
 } catch (err) {
   res.status(500).send({ error: 'failed to fetch data' })
 }
}
You can also try this code with Online Javascript Compiler
Run Code

Frequently Asked Questions (FAQs)

1.What is Next.js?

Next.js is a React framework that allows you to create single-page Javascript apps. This framework has various advantages for our clients' applications and our development team. 

2.What is an API route in Next.js?

API (Application Programming Interface) in Next.js is a software intermediary that allows two applications to talk to each other.

Key Takeaways

In this article, We learned about the API routes in next.js. We also learned the concept of Dynamic API routes and API structure in Next.js. We also saw how to send responses in JSON and HTTP formats.

For more information about the react framework for frontend development, get into the entire Frontend web development course, and to learn more about backend development go through the Backend web development course.

Happy Learning!
 

Live masterclass