/

How to Utilize Next.js API Routes for Improved SEO

How to Utilize Next.js API Routes for Improved SEO

Discover the incredible capabilities of Next.js API routes to effortlessly create API endpoints within your Next.js application.

In addition to serving web pages as page routes, Next.js provides the ability to create API routes. This powerful feature allows Next.js to act as both the frontend and backend, facilitating seamless data storage and retrieval through JSON fetch requests.

API routes are located within the /pages/api/ folder and are mapped to the /api endpoint. This functionality proves exceptionally valuable when building applications.

Within API routes, you write Node.js code instead of React code, transitioning seamlessly from frontend to backend development.

For instance, let’s assume you have a /pages/api/comments.js file whose purpose is to return a blog post’s comments in JSON format. Suppose you have a comments.json file containing a list of comments:

1
2
3
4
5
6
7
8
[
{
"comment": "First"
},
{
"comment": "Nice post"
}
]

You can utilize the following code snippet to return the comments list to the client:

1
2
3
4
5
import comments from './comments.json'

export default (req, res) => {
res.status(200).json(comments)
}

This code will listen on the /api/comments URL for GET requests. You can test it by making a request using your browser.

API routes also support dynamic routing, just like pages. You can create a dynamic API route using the [] syntax. For example, create a /pages/api/comments/[id].js route to retrieve comments specific to a post ID.

Inside the [id].js file, you can access the ID value by referencing req.query.id:

1
2
3
4
5
import comments from '../comments.json'

export default (req, res) => {
res.status(200).json({ post: req.query.id, comments })
}

You can observe the above code in action by accessing the appropriate URL.

Note that in dynamic pages, you would import useRouter from next/router, retrieve the router object using const router = useRouter(), and access the id value using router.query.id. However, in the server-side, the query is attached to the request object, simplifying the process.

For POST requests, the same default export handles the functionality. To differentiate between POST, GET, and other HTTP methods (such as PUT and DELETE), you can check the req.method value:

1
2
3
4
5
6
7
8
9
10
11
12
13
export default (req, res) => {
switch (req.method) {
case 'GET':
//...
break
case 'POST':
//...
break
default:
res.status(405).end() //Method Not Allowed
break
}
}

In addition to req.query and req.method, you can access cookies through req.cookies and the request body through req.body.

Next.js utilizes the Micro library under the hood, which enables asynchronous HTTP microservices. You can incorporate any Micro middleware in your API routes to enhance functionality.

tags: [“Next.js”, “API Routes”, “Backend Development”, “JSON”, “Seemless Data Storage”, “Microservices”]