How to use Cookies in Next.js(Pages Router) with Redux TK
Tags: redux, nextjs, javascript, typescript
Published: 2023-08-08 16:47:17

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.

```sh
yarn add @reduxjs/toolkit react-redux next-redux-wrapper
```

Or

```sh
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**

```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';

```jsx
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**

```sh
yarn add cookies-next
```

Or

```sh
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**

```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**.

```js
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.

```js
import { getCookie } from 'cookies-next';

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

## Reducer/Slice

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

**Reducer**

```js
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**

```js
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

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.