DEV Community

Cover image for How to use Cookies in Next.js(Pages Router) with Redux TK
Arthur Arakelyan
Arthur Arakelyan

Posted on • Updated on

How to use Cookies in Next.js(Pages Router) with Redux TK

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
Enter fullscreen mode Exit fullscreen mode

Or

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

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

/store
    // your-reducers/slices
    /store/configureStore.js
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

Cookies

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

yarn add cookies-next
Enter fullscreen mode Exit fullscreen mode

Or

npm install cookies-next
Enter fullscreen mode Exit fullscreen mode

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: {},
  };
});
Enter fullscreen mode Exit fullscreen mode

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

import { setCookie } from 'cookies-next';

setCookie('auth_token', 'XXXXXXXXXXXXXX');
Enter fullscreen mode Exit fullscreen mode

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') || '',
};
Enter fullscreen mode Exit fullscreen mode

Reducer/Slice

I have prepared 2 examples, first for reducer, and the second is 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);
});
Enter fullscreen mode Exit fullscreen mode

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;
    },
  },
});
Enter fullscreen mode Exit fullscreen mode

Conclusion

We studied the topic of using cookies in the Redux store for Next.js apps. Surely, now you can integrate the auth token storing logic in server side, that means there is no need to pass the cookies through the props for every page.

Top comments (0)