How to Create Magento 2 Headless NextJs Setup

Magento 2 as a backend, using Magento’s APIs OR GraphQL, and creating a Next.js frontend

Requisites:

  • Magento is installed and running.
  • Node.js installed.
  • Basic understanding of both Magento 2 and Next.js.

S1: Magento 2 REST and GraphQL APIs

  • Magento 2 Running with REST and GraphQL APIs
  • Magento 2 instance is publicly accessible if you use the front and will be hosted separately.

S2: Create a New Next.js Project

  • Initialize the Next.js Project

npx create-next-app shop-nextjs
cd shop-nextjs

  • Install Dependencies

npm install @apollo/client graphql isomorphic-fetch

S3: Configure Apollo Client

Connect NextJs Project with Magento 2 Via GraphQL API using Apollo Client

Create an Apollo Client Configuration: Create a new file lib/apolloClient.js:

Provide the Apollo Client to the Application:

Wrap your application in the ApolloProvider. Update app/layout.tsx :

S4 : Get Data from Magento

Use GraphQL queries to fetch data from Magento. For example, to fetch products:

Create a Products Component:

Create a new file components/Products.js:

Use the Products Component in a Page: Update app/page.tsx:

import Products from ‘../components/Products’;

S5: Styling and Additional Features

  • Add CSS or use a CSS-in-JS solution to style As per design.
  • Implement additional features like product filtering, and pagination.

S6: Deployment

Deploy Next.js application to a platform like Vercel, or any other hosting provider that supports Node.js applications. Magento backend is accessible from your deployed frontend.

Summary

By following these steps, you can create a headless Magento 2 setup with a Next.js frontend. This setup allows for a highly customizable and performant eCommerce solution, leveraging the strengths of both Magento 2’s robust backend capabilities and Next.js’s modern frontend features.

Start your Magento 2 Headless NextJS Development with CynoInfotech

CynoInfotech

CynoInfotech was founded in 2019, in Ahmedabad, Gujrat. we have a trusted Web Development and Design Company that helps businesses in streamlining their operations through Magento 2 Extension and advanced modern technology solutions.

Let’s connect