Scaffolding redux-toolkit in NextJs
Tags: javascript, nextjss, node, mern
Published: 2023-12-17 19:41:25

Previously you saw, how to make API via Node. Here is this [tutorial](url). 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k9x576aszqr5gl8oq0vi.png)

**Step-1 : Install reduxt toolkit and other packages**

```
npm install @reduxjs/toolkit
npm install react-redux
```
**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',
      
  
    },
  }

```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kvyj02sht5llge53wgu1.png)

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>
    )
}

```
**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) => ({}),
});


```
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>
  )
}

```
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](https://dev.to/kamruzzaman/api-setup-in-nextjs-3gen)


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 😇]