NextJS is a framework for building production-ready applications. As we all know, a production application can have static pages as well as backend APIs. NextJS helps us create both. In this post, we will specifically learn how to create NextJS API Routes for backend logic.

In case you are new to NextJS, do check out this post on getting started with NextJS.

1 – The Need for Backend API Routes

As discussed earlier, many websites don’t have just HTML pages to display information. They also have functionality where information is collected from the user and stored/processed in some way. For example, you can have features such as:

  • Collecting user feedback
  • Newsletter signups where user submits their email address

To perform such functionalities, we need to build some backend services to collect the information and store it in a database. These services are normally built as REST APIs.

In REST approach, we can have many endpoints or routes and HTTP methods. For each method and route, we need to execute some server side code. Basically, API routes are special kinds of path used for fetching and storing data on the server. For example, we can have an API route /api/feedback to collect user feedback.

In the context of NextJS, API routes are URLs that don’t return simple HTML pages but instead provide REST APIs that return some data.

2 – Creating NextJS API Routes

As you might be aware, NextJS supports file-based routing to expose different routes for different pages. This is done by creating appropriate React components inside the pages folder of your project.

Creating an API route for NextJS is also equally simple. The only condition is that we have to create a special folder api within the pages folder.

Within the api folder, we can then create handlers for incoming requests. See below example of a request handler for receiving incoming feedback from the user.

import fs from 'fs';
import path from 'path';

function buildFeedbackPath() {
    return path.join(process.cwd(), 'data', 'feedback.json');
}

function extractFeedbackData() {
    const filePath = buildFeedbackPath()
    const fileData = fs.readFileSync(filePath);
    return JSON.parse(fileData);
}

function handler(req, res) {
    if (req.method === 'POST') {
        const email = req.body.email;
        const feedbackText = req.body.text;

        const newFeedback = {
            id: new Date().toISOString(),
            email: email,
            text: feedbackText
        };

        //store the feedback data in a file
        const filePath = buildFeedbackPath()
        const data = extractFeedbackData(filePath);
        data.push(newFeedback);
        fs.writeFileSync(filePath, JSON.stringify(data));
        res.status(201).json({ message: 'Feedback logged', feedback: newFeedback });
    } else {
        res.status(405).json({ message: 'Not supported currently!' });
    }
}

export default handler;

This is a simple JavaScript code. The main point is that this code will only run on the server and will never be exposed to the client.

In the above code, we have a handler function where we check whether the incoming HTTP request method is of type POST. If yes, we extract the email and feedbackText from the request body and save the data in a JSON file (feedback.json) within our project. Instead of a file, we could have also saved the data in a database table.

Once we have created this file, we can simply access the API using HTTP POST request on http://localhost:3000/api/feedback.

3 – Using the NextJS API Routes

While we can directly call the REST API using any client, we usually want to use the API endpoints within our application.

Since our API route is supposed to collect feedback, let us create a tiny component for users to submit the feedback.

See below code from the /pages/index.js file.

import { useRef } from 'react';

function HomePage() {

  const emailInputRef = useRef();
  const feedbackInputRef = useRef();

  function submitFormHandler(event) {
    event.preventDefault();

    const enteredEmail = emailInputRef.current.value;
    const enteredFeedback = feedbackInputRef.current.value;

    const requestObj = { email: enteredEmail, text: enteredFeedback };

    fetch('/api/feedback', {
      method: 'POST',
      body: JSON.stringify(requestObj),
      headers: {
        'Content-Type': 'application/json'
      }
    }).then(response => response.json())
      .then((data) => console.log(data));
  }

  return (
    <div>
      <h1>The Home Page</h1>
      <form onSubmit={submitFormHandler}>
        <div>
          <label htmlFor="email">Your Email Address</label>
          <input type="email" id="email" ref={emailInputRef} />
        </div>
        <div>
          <label htmlFor="feedback">Your feedback</label>
          <textarea rows="5" id="feedback" ref={feedbackInputRef} />
        </div>
        <button>Send</button>
      </form>
    </div>
  );
}

export default HomePage;

This is a typical React component. We use the special useRef hook to read data from input fields for email and feedback comments. The input fields are contained within a form.

After collecting the input in the submitFormHandler() method, we use JavaScript fetch API to make a HTTP POST request to /api/feedback. This will basically invoke the REST API route we created in the previous section and the data will be stored in the file.

We can now start the application and test it at http://localhost:3000.

Conclusion

With this, we have learnt how to create NextJS API routes for adding backend logic to our NextJS applications.

NextJS makes it extremely easy to wire backend and front-end code together to build production ready applications.

Want to learn more about NextJS? Check out this post on how to add meta tags in NextJS.

If you have any comments or queries about this post, please feel free to mention them in the comments section below.

Categories: NextJS

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *