Hire Me

Next.js API Routes - Building Backend Functionality with Ease

Updated: 03/09/2022

Setting up API Routes

To use API Routes in your Next.js application, follow these steps:

  • Create a new directory called api at the root of your Next.js project.

  • Inside the api directory, create a new file with the desired API route name, for example, example.js. This file will contain the serverless API logic.

// api/example.js export default (req, res) => { if (req.method === "GET") { // Handle GET request res.status(200).json({ message: "This is a GET request!" }); } else if (req.method === "POST") { // Handle POST request const { name } = req.body; res .status(200) .json({ message: `Hello, ${name}! This is a POST request!` }); } else { // Handle other request methods res.status(405).json({ message: "Method Not Allowed" }); } };

In this example, we have defined a handler for GET and POST methods. You can add logic based on the request method and process the request accordingly.

  • Next, we need to configure our Next.js application to recognize the API Routes. Open the next.config.js file (create one if it doesn't exist) and add the following configuration:
// next.config.js module.exports = { async rewrites() { return [ { source: "/api/:path*", destination: "/api/:path*", }, ]; }, };

This configuration will allow Next.js to recognize the /api route and forward the requests to the corresponding API functions.

  • Now, you can access your API routes at /api/[routeName]. For example, if your route file is named example.js, you can access it at /api/example.

Calling the API Routes

To call the API routes from the client side of your Next.js application, you can use fetch or any other HTTP client library.

Here's an example of calling the API route we defined earlier:

// pages/index.js import { useState } from "react"; function HomePage() { const [message, setMessage] = useState(""); const fetchData = async () => { try { const response = await fetch("/api/example", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ name: "John" }), }); const data = await response.json(); setMessage(data.message); } catch (error) { console.error(error); } }; return ( <div> <h1>Welcome to my Next.js app!</h1> <button onClick={fetchData}>Call API</button> <p>{message}</p> </div> ); } export default HomePage;

In this example, we call the /api/example route using the fetch function. We send a POST request with the name "John" in the request body. The response data is displayed on the page.

Conclusion

Next.js API Routes provide a simple and convenient way to build backend functionality within your Next.js applications. In this blog post, we learned how to set up API Routes, handle different HTTP methods, and call the routes from the client side.