Scaffolding redux-toolkit in NextJs

kamruzzaman

syed kamruzzaman

Posted on December 17, 2023

Scaffolding redux-toolkit in NextJs

Previously you saw, how to make API via Node. Here is this tutorial. Now in this tutorial, we are focused on integrating this API in our Next.js App. Let's dive in!

UI Design
Basic UI design I am already done for easy our task. Below is this UI project link. Here we use TailwindCss.

https://github.com/kamruzzamanripon/next-movie-ui

In this UI app, we can see the app folder, in which you see the page.js file. This is the home page and the other page shows folder-wise. Like make-category it means create category and its URL is /make-category. I was trying to make it simple to understand.

Image description

Step-1 : Install reduxt toolkit and other packages

npm install @reduxjs/toolkit
npm install react-redux
Enter fullscreen mode Exit fullscreen mode

Step-2 : Configure API Url
Open your next.config and do this

module.exports = {
    reactStrictMode: true,
    images:{
      domains:['images.unsplash.com', 'via.placeholder.com', '127.0.0.1', 'laravelapi.kamruzzaman.xyz'],
    },
    env: {
      API_ROOT_URL:'http://localhost:8000/api',
      baseUrl:'http://127.0.0.1:8000/api/v1/frontend',


    },
  }

Enter fullscreen mode Exit fullscreen mode

Here we defined API_ROOT_URL and setup domains '127.0.0.1' for image.

Step-3 : Make some folder

In app folder we create reduxStore folder and in this folder we create below file

  1. provider.js
  2. store.js

and make another folder like features And this inside this folder create the below folder and file

  1. api [Folder]
    • apiSlice.js
  2. auth [Folder]
    • authApi.js
    • authSlice.js
  3. category [Folder]
    • categoryApi.js
    • categorySlice.js
  4. movie [Folder]
    • moviesApi.js
    • movieSlice.js

Image description

Now we copy and paste the corresponding file of code

Store.js

'use client';

import { configureStore } from "@reduxjs/toolkit";
import { apiSlice } from "./features/api/apiSlice";
import authSliceReducer from "./features/auth/authSlice";
import counterReducer from './features/counter/counterSlice';
import movieSliceReducer from "./features/movie/movieSlice";

export const store = configureStore({
    reducer:{
        [apiSlice.reducerPath]: apiSlice.reducer,
        auth: authSliceReducer,
        movies: movieSliceReducer,
        conter: counterReducer
    },
    devTools: process.env.NODE_ENV !== "production",
    middleware: (getDefaultMiddlewares) =>
        getDefaultMiddlewares().concat(apiSlice.middleware),
})

Provider.js
'use client';

import { Provider } from "react-redux";
import { store } from "./store";

export function Providers({children}){
    return (
        <Provider store={store}>
            {children}
        </Provider>
    )
}

Enter fullscreen mode Exit fullscreen mode

apiSlice.js

'use client';
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";

// Function to get the auth token from localStorage
function getAuthToken() {
  if (typeof window !== 'undefined') {
    const authData = JSON.parse(localStorage.getItem("auth"));
    return authData?.accessToken;
  }
  return undefined;
}

export const apiSlice = createApi({
    reducerPath: "api",
    baseQuery: fetchBaseQuery({
        baseUrl: process.env.API_ROOT_URL,
        prepareHeaders: (headers, { getState }) => {
            // Use the token from the state if available, otherwise try to get it from localStorage
            const token = getState()?.auth?.accessToken || getAuthToken();

            if (token) {
                headers.set("Authorization", `Bearer ${token}`);
            }

            return headers;
        },
    }),
    tagTypes: [],
    endpoints: (builder) => ({}),
});


Enter fullscreen mode Exit fullscreen mode

Here baseUrl, we already define in our next.config.js file. Also we set up of Authorization token. If API Url sends an Authorization token then we store headers for access to other pages.
Now we go layout.js file and do this

import { Inter } from 'next/font/google'
import Footer from './Footer'
import Header from './Header'
import './globals.css'
import { Providers } from './reduxStore/provider'

const inter = Inter({ subsets: ['latin'] })

export const metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
}

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body className={inter.className}>
        <Providers>
        <Header />
        <main>{children}</main>
        <Footer />
        </Providers>
      </body>
    </html>
  )
}

Enter fullscreen mode Exit fullscreen mode

Here we wrapped up redux store in our app.
Next we set up Authentication and Other API. Here is this Tutorial-

API Setup in NextJs. Link

full Project github
Node
https://github.com/kamruzzamanripon/node-movie-api
NextJs
https://github.com/kamruzzamanripon/next-movie-ui-with-node-api
NextJs UI
https://github.com/kamruzzamanripon/next-movie-ui

That's all. Happy Learning :) .
[if it is helpful, giving a star to the repository 😇]

💖 💪 🙅 🚩
kamruzzaman
syed kamruzzaman

Posted on December 17, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Scaffolding redux-toolkit in NextJs
javascript Scaffolding redux-toolkit in NextJs

December 17, 2023