Mastering Cookies in Next.js: A Step-by-Step Guide to Integrating with Redux TK

Mastering Cookies in Next.js: A Step-by-Step Guide to Integrating with Redux TK

In today's world, online security is incredibly important, especially when it involves user authorization. Sometimes, you need to access data that's only available to authorized users with an authentication token.

Luckily, you can accomplish this by using Next.js and Redux store through getServerSideProps. But where do you store this token for safekeeping? In this helpful article, you'll discover how to use cookies-next to get and store the user's auth token in the Redux Store through getServerSideProps, offering an added layer of security to your app.

Additionally, this approach isn't limited to just auth tokens - you can also store other important strings, such as the theme of your website.

You'll find detailed instructions and code samples in this guide to assist you in developing a secure authentication system for your Next.js application.

 

Auth token in Next.js



Sometimes you need to use the auth token in Next.js to get data from Back-end which is available only for a user with authorization, then get data from Redux store through the getServerSideProps.

As we know, the user’s auth token can be stored in the Cookies.

 

In this article you will learn how to get the Cookies and store them in the Redux store in getServerSideProps, then have the data from cookies at the first render of the client.


Note: This can be useful not only for auth token, you can use it to store any string, like the theme of the website.

 

Initialize Redux Store

 

Let’s begin with installing the libraries for Redux.

 

$ yarn add @reduxjs/toolkit react-redux next-redux-wrapper

Or

$ npm install @reduxjs/toolkit react-redux next-redux-wrapper

For Redux store we are going to use the structure below:

/store

// your-reducers/slices
    /store/configureStore.js

 

ConfigureStore.js

 

import { configureStore } from '@reduxjs/toolkit';
import { createWrapper } from 'next-redux-wrapper';

const store = configureStore({
  reducer: {}, // Here goes your reducer
});

export const wrapper = createWrapper(() => store);

export default store;

 

Then we are going to add the store Provider.

 

pages/_app.js

 

import { Provider } from 'react-redux';
import { wrapper } from '@/store/configureStore';

export default function App({ Component, pageProps }) {
  const { store, props } = wrapper.useWrappedStore(pageProps);

  return (
    <Provider store={store}>
      <Component {...props.pageProps} />
    </Provider>
  );
}

Cookies

 

For working with cookies we are going to install cookies-next

 

$ yarn add cookies-next

Or

$ npm install cookies-next

Now we can use getServerSideProps in all pages with the next-redux-wrapper, let’s try it in the home page.



pages/index.js

 

import { getCookies } from 'cookies-next';
import { wrapper } from '@/store/configureStore';

export const getServerSideProps = wrapper.getServerSideProps((store) => async ({ req, res }) => {
  const cookies = getCookies({ req, res }); // Get cookies in server side

  store.dispatch({ // Dispatch GET_COOKIES action
    type: 'GET_COOKIES',
    payload: {
      cookies, // Send the cookies in GET_COOKIES action
    },
  });

  return {
    props: {},
  };
});

 

First, let’s make sure that the auth token exists in cookies.

 

import { setCookie } from 'cookies-next';

setCookie('auth_token', 'XXXXXXXXXXXXXX');

 

Then we will need to create an initial state for the reducer/slice, then get the auth_token from cookies for the client side.

 

import { getCookie } from 'cookies-next';

const initialState = {
  authToken: getCookie('auth_token') || '',
};

Reducer/Slice



I have prepared 2 examples, the first for reducer, and the second for slice

 

Reducer

 

import { createReducer } from '@reduxjs/toolkit';

const auth = createReducer(initialState, (builder) => {
  builder
    .addCase('GET_COOKIES', (state, { payload }) => {
      const { cookies } = payload;

      state.authToken = cookies.auth_token;
    })

    .addDefaultCase((state) => state);
});

Slice

 

import { createSlice } from '@reduxjs/toolkit';

const auth = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    // ...
  },
  extraReducers: {
    GET_COOKIES: (state, { payload }) => {
      const { cookies } = payload;

      state.authToken = cookies.auth_token;
    },
  },
});

 

Conclusion

 

During our research of the importance of cookies in the Redux store for Next.js applications, we gained deep insights into the best practices of integrating authentication token storage logic on the server side.
By implementing this approach, you can effectively eliminate the need to pass cookies through the props of every page, significantly reducing the complexity of your codebase and boosting the overall performance of the application.

With this new knowledge, you are now well-equipped to optimize your Next.js app's authentication process by the way cookies are used, resulting in improved functionality, better user experience, and increased security.