Read More
Read More
Menu Close

    How to work with Magento’s Rest API in Next js

    This blog will show an example of how we can implement Rest API in the next js with Magento 2.

    We can easily create a REST API in our Next.js app by using the built-in API routes.

    About Rest API

    REST stands for Representational State Transfer. It’s a software architectural style for implementing web servicesWeb services implemented using the REST architectural style are known as the RESTful web services.

    Create an app in Next js

    To create the Next app you can visit our blog by clicking here.

    We are also giving here commands to create the next app simply.

    Searching for an experienced
    Magento 2 Company ?
    Read More
    npx create-next-app rest_app
    # or
    yarn create next-app rest_app

    After the installation follows the below steps to use Rest API.

    Rest API implementation with Magento 2

    Simply we can use Magento API using the below steps:

    Create a page in pages folder pages/getToken.js and use the below code in your page.

    For example, here we are getting customer token. To get the token we have to send username and password to validate at the Magento end. Details must be correct else you will get this message: “The account sign-in was incorrect or your account is disabled temporarily. Please wait and try again later.”

    Let’s create a page with pages/getToken.js

    import React, { useState, useEffect } from "react";
    const getToken = () => {
      const [token, setToken] = useState();
      const credentials = {
        username: "email",
        password: "password",
      useEffect(() => {
        try {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
              body: JSON.stringify(credentials),
            .then((res) => res.json())
            .then((data) => {
              setToken(data); // Here we are setting token in state to use in our component.
        } catch (error) {
      }, []);
      return (
        <div style={{ color: "green", textAlign: "center", fontWeight: "700" }}>
          {token ? "Customer Token: " + token : "Loading..."}
    export default getToken;

    Result will be like this:

    On Loading result
    Result with customer token

    In the above code, we are using the useState hook to display customer token and useEffect hook is used to handle the request. We have passed a [] array to call it once.

    Just copy and use it by changing your host and user credentials.

    If you face any issues regarding this blog then please comment below.

    Happy coding 🙂

    . . .
    Discuss on Helpdesk

    Leave a Comment

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

    Be the first to comment.

    Back to Top