~/javascript/next-js-strapi-get-api-common-rest-api-class.md

How to Integrate Next.js with Strapi Backend and Create a common utility class for REST APIs

3 min readMay 04, 2021by Gorav Singal#javascript#next-js#bootstrap
// TL;DR

Build a reusable REST API utility class in Next.js for Strapi backend integration that handles authenticated requests with JWT and provides common CRUD methods.

How to Integrate Next.js with Strapi Backend and Create a common utility class for REST APIs

Introduction

In this post, we will integrate Next.js with Strapi fully. And we will create a class which will call REST APIs to our backend. We will also see a sample index.jsx file to fetch all articles.

And, we will start building from these building blocks.

So far, we have seen:

Create an REST Client API Class

Since we will be calling REST APIs in almost every page. It is better to write a common code which will wrap our logic of calling APIs and JWT tokens.

Lets write an /components/api/api_client.js

import { getSession } from 'next-auth/client'
import axios from 'axios'

class ApiClient {

  async getAuthHeader () {
    let header = {}
    const session = await getSession();
    if (session.jwt) {
      header = {Authorization: `Bearer ${session.jwt}`};
    }
  
    return header;
  }

  async saveArticle(args) {
    console.log('Saving Article', args);
    const headers = await this.getAuthHeader();
    try {
      let { data } = await axios.post(
        `${process.env.NEXT_PUBLIC_API_URL}/articles`, 
        {
          title: args.title,
          body: args.body
        },
        {
          headers: headers,
        }
      )
      return data;
    } catch (e) {
      return e;
    }
  }

  async updateArticle(args) {
    console.log('Updating Article', args);
    const headers = await this.getAuthHeader();
    try {
      let { data } = await axios.put(
        `${process.env.NEXT_PUBLIC_API_URL}/articles/${args.id}`, 
        {
          title: args.title,
          body: args.body
        },
        {
          headers: headers,
        }
      )
      return data;
    } catch (e) {
      return e;
    }
  }

  async getArticleById(id) {
    try {
      let { data } = await axios.get(
        `${process.env.NEXT_PUBLIC_API_URL}/articles/${id}`
      )
      return data;
    } catch (e) {
      return e;
    }
  }

  async getArticleBySlug(slug) {
    let {data } = await axios.get(
      `${process.env.NEXT_PUBLIC_API_URL}/articles?slug=${slug}`
    );
    return data;
  }

  async getArticles() {
    let {data } = await axios.get(
      `${process.env.NEXT_PUBLIC_API_URL}/articles`
    );
    return data;
  }

  async uploadInlineImageForArticle(file) {
    const headers = await this.getAuthHeader();
    const formData = new FormData();
    formData.append('files', file);
    try {
      let { data } = await axios.post(
        `${process.env.NEXT_PUBLIC_API_URL}/upload`, 
        formData,
        {
          headers: headers,
        }
      )
      return data;
    } catch (e) {
      console.log('caught error');
      console.error(e);
      return null;
    }
  }
}

module.exports = new ApiClient();

We have wrapped all api code in a class. Now, who so ever need to call rest apis, can use this class.

Example Index.jsx using this apiClient class

import Head from 'next/head'
import SimpleLayout from '../components/layout/simple'
import apiClient from '../components/api/api_client'

export default function Home(initialData) {
  return (
    <SimpleLayout>
      <section className="jumbotron text-center">
        <div className="container">
          <h1>Subscribe to GyanByte</h1>
          <p className="lead text-muted">
            Learn and Share
          </p>
        </div>
      </section>

      <div className="row">
      <div>
        {initialData.articles && initialData.articles.map((each, index) => {
          return(
            <div key={index}>
              <h3>{each.title}</h3>
              <p>{each.body}</p>
            </div>
          )
        })}
      </div>
      </div>
    </SimpleLayout>
  )
}

export async function getServerSideProps({req}) {
  try {
    let articles = await apiClient.getArticles();
    console.log(articles);
    return {props: {articles: articles}};
  } catch (e) {
    console.log('caught error');
    return {props: {articles: []}};
  }
}

The code is simple to use. The function getServerSideProps is a special method by Next.js and is executed the first thing in this file index.jsx. And, we are fetching all articles here, and returning the data.

Now, this data will be received by our index.jsx react component. Here, we have used a function component. It will receive the data as props, and you can use it in the way you want.

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

How to use Draft.js WYSWYG with Next.js and Strapi Backend, Edit/Update Saved Article

How to use Draft.js WYSWYG with Next.js and Strapi Backend, Edit/Update Saved Article

Introduction This post is in contuation of our previous post: How to use Draft…

Create Articles with Image Upload Using Draft.js, Next.js, and Strapi

Create Articles with Image Upload Using Draft.js, Next.js, and Strapi

Introduction In this post, we will use in Next.js with strapi. And, we will…

Next.js - How to Get Session Information in Server Side vs Client Side iusing Next-auth

Next.js - How to Get Session Information in Server Side vs Client Side iusing Next-auth

Introduction Next-auth is a fantastic library for abstracting handling of…

How to Use Signin Signout Buttons in Next.js bootstrap project with Next-auth

How to Use Signin Signout Buttons in Next.js bootstrap project with Next-auth

Introduction In our last post, we have seen a full example of Next.js with…

Next.js Bootstrap Starter - Nice Template Navbar Header and Few Pages

Next.js Bootstrap Starter - Nice Template Navbar Header and Few Pages

Introduction In this post, we will do following: create a Next.js project…

Nextjs - How to Build Next.js Application on Docker and Pass API Url

Nextjs - How to Build Next.js Application on Docker and Pass API Url

Introduction In this post we will see: How to prepare a docker image for your…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…