Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Scaffolding redux-toolkit in NextJs
syed kamruzzaman
syed kamruzzaman

Posted on

Scaffolding redux-toolkit in NextJs

Previously you saw, how to make API via Node. Here is thistutorial. 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/toolkitnpm install react-redux
Enter fullscreen modeExit fullscreen mode

Step-2 : Configure API Url
Open yournext.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 modeExit 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 modeExit fullscreen mode

apiSlice.js

'use client';import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";// Function to get the auth token from localStoragefunction 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 modeExit 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 golayout.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 modeExit 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 😇]

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Frontend and Backend Full Stack Developer
  • Location
    Dhaka, Bangladesh
  • Education
    Master of Economic
  • Joined

More fromsyed kamruzzaman

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp