A beginner guide for Redux with Next.js

Bhavik Bamania
8 min readFeb 26, 2019

--

JWT Authentication with Redux in Next.js

Redux is not a new thing, and there are a hell lot of articles demos, to begin with so what is the purpose of drafting this article over medium? I know you must be wondering after reading. Well, to be frank with you all readers, the purpose of this article to cope with the fear of Redux and the misconceptions of Redux that we all keep in our mind. When I am talking about “We” I am including myself as well.

A week before I was afraid of Redux, you know the reason? Well, there are a couple of reasons,

  1. I haven’t called API in React all I did is designing, in words, I haven’t tried to look into this. I told myself that it's not my cup of tea until I actually tried to look into it.
  2. I don’t know the importance of Redux.

So, if you are into the same page then you are at the right place and I am assuring you, after this article, you won’t fear anymore from Redux instead you will start loving it. So, let’s kickstart with the proceedings.

Prerequisite

  • An API in your favorite framework, which implements JWT authentication.
  • Basic knowledge of JS, React.
  • Node js and create-next-app CLI installed on your system.

Setup

If you have npm and create-next-app is installed then you can simply follow the following command

create-next-app next-jwt-auth-redux

This command will craft you a scaffolding for nextjs, the reason behind using Next.js is I want to avoid route management you can choose whatever you like to, in place of Next.js. I recommend you to implement this in your existing react/react native projects, but make sure you create a backup for your existing folder.

Once this command creates a basic template for your application you can start your development with this command

npm run dev

you will see your server has started on http://localhost:3000/

Now what? Wait, we were supposed to use Redux with JWT authentication, so how can we do that with the design which you have right now? The answer is simple we will make a signup and login form in order to implement JWT authentication and that token we will stored in our store via Redux, but we will cover that part later first thing first we need to setup the architecture of Redux.

Architecture

In order to work with React Redux the very first thing you need to do is to setup the architecture, install redux into your project by the following command:

npm install redux --save

Now, we will need to install react-redux. It is the official binding of react for redux. To install react-redux just hit the following command.

npm install react-redux --save

Now, we will need a middleware, for redux to support async data flow. So, here in this article, I am using a redux thunk to install redux thunk use the following command.

npm install redux-thunk --save

Now, the last part of the setup, at last, we will install a next-redux-wrapper. It is a wrapper for next.js application, to implement this first we need to install it and then wrap it in our _app.js file. To install use this command

npm install next-redux-wrapper --save

Now, we have installed all the dependencies successfully here as of now and now it is time to move to the setup folder structure.

There is nothing fancy in the folder structure all you need to create a folder and name it as redux.

The redux will have two sub-folders namely, action and reducers. Now, you must be thinking what the heck are these folders? Recall, the redux diagram you will understand what these folders are going to contain.

Redux architecture for better understanding.
  • Action: In this folder, you will keep all your action files. You will understand this when we will implement in your code.
  • Reducer: In this folder, reducers will be kept, reducers helps to communicate action with the store.
  • Store: Store is where your data is stored. When you are working with web application store use cookies to store your application data, and when you are working with react native async storage will be used to store your data.

Now, we have done enough with our theory, let’s exercise our hand and first create the actions directory and create a file named as authActions.js and paste the following code.

If you have noticed, we have an import here axios but we haven’t installed it yet in our project so, let’s install this package by the following command. We will use axios for API calls.

npm install axios --save

But wait, we are importing some unknown files which we haven’t created yet. So, we will create the dependencies first line by line and we will try to understand what they are doing here.

First, we are importing types so let’s create types.js in your redux directory and add the following code.

The basic purpose of this file to keep all the types of API calls, for instance, we are starting with authenticate and deauthenticate here.

Next, I have imported config.js file this file will have the base URL of API, you can keep it like that or you can keep it in your own preferred way. This file is optional. If you are not using this file then remove it from your code.

And now we have the last import in our file, that is, cookie, for that first we need to create utils directory and then create cookie.js in it.

Oh wait, one more import, well we need to install js-cookie to use cookies in redux store. Install it with this command.

npm install js-cookie --save

Now, we need this file to communicate with our reducers, however, we haven’t created our reducers yet, we will create our reducers later on first we will create the index file which will connect.

so, what does this code mean? It’s nothing just we are importing all the functions which we have created in authActions.js.

Now, we are almost done with our setup and now we are just short to create our reducers. So, to create our reducer let’s create reducer sub-directory in our redux directory and then create index.js inside it.

As you can see we are importing authReducer so let’s create this file

So, what is the purpose of both these files? Well, recall the redux diagram actions are called from UI component, and then after processing these action returns the payload and these payloads are received by the Reducer. Consider reducer as a middleman between producer and a storekeeper. The producer produces the goods and sells them to the middleman and then the middleman sells the received goods to the storekeeper. Similarly, in the redux environment, an action is a producer which collects the resources and produces an output then the action passes it on to reducers (middleman) and now the middleman will pass the received payload to the store. In other words, it will update the store.

Now, we will create our store which reducer is seeking to update. Create an index.js file in redux root directory.

In this file we are initializing the redux store by passing initial state and instance of reducer, we are applying thunk middleware to support async data flow.

Now everything is done from the redux setup point of view. So, now we can move on to the integration of redux into our app. The integration of redux is not that lengthy process instead it requires only two steps

  • Wrap your app with Provider.
  • Get the initial state of the redux store.

So, to wrap your app with Provider we need to create a file in our pages directory with name _app.js

This is the basic will which will help the app to get connected with the store.

Now we are ready to call to our API feel free to create API using JWT auth and give a try with this.

With whatever we have done so far we can register a user. So, let’s do it since we haven’t designed our forms, for registration and login, so let's begin with that part, also you can do it in your own preferred way but make sure you put everything at the right place. Here is how we will calling the registration API

Here we need to create one more file named as initialize.js you can see we have called it in our signup code. So, let’s create this file first then we will see why we need this file.

Okay, now as you can see this file is like an inspector, it will keep a check on the token, once our app is loaded it will fetch the token from cookie and attempts to reauthenticate the token via a reauthenticate function, however, we haven’t written our reauthenticate function so, to write that function go to authActions.js file and paste the following code

const reauthenticate = (token) => 
return (dispatch) => {
dispatch({type: AUTHENTICATE, payload: token});
};
};

Now once registration is complete let's try to login into the system, to implement login functionality into our system paste the following code into authActions.js file.

Now, next, we are going to design the Login form, where we will implement the login API.

Let’s try this code in our editor and see what we got here.

If we are on the same page, then we have successfully logged in into our system. Now we need to tell the system what to do when a user is logged in. So, let’s try to fetch logged in the user profile with the token we have in our store. First, we will create an action.

Now, we need to modify the reducer function to the incoming payload from getUser function. A couple of things we need to do for that, first let’s add USER type in type.js like that

export const USER = 'user';

now update your authReducer.js

case USER:
return Object.assign({}, state, { user: action.payload });

now your authReducer.js will look like this

Now, to complete user login cycle we need to implement Logout, logging out is quite simple in JWT. All we need to empty the token that we have in our store. Update your authActions.js file with this code.

// removing the tokenconst deauthenticate = () => {
return (dispatch) => {
removeCookie('token');
Router.push('/');
dispatch({type: DEAUTHENTICATE});
};
};

The final authActions.js file will look like this

Now, following the redux cycle, we need to update our authReducers

case DEAUTHENTICATE:
return { token: null };

Conclusion

So, we have implemented Redux using our API with JWT. I hope you have understood what is redux and how we can setup redux architecture in our application this is not a final frozen architecture you can mold it as per your thinking it is just a basic architecture for a beginner. I hope this article will help you to rid of the fear of Redux. You can find the entire source code of this article in this git repo.

If you liked my article then you can keep the clap button pressed for a few moment, you can follow me on medium, twitter, instagram, your appreciation will motivate to write more! Thank you for your time until next time!

--

--

Bhavik Bamania

Poet . Aspiring Writer . Boring Philosopher . Extreme Thinker . Web Designer . Web Developer . https://www.bhavikji.com/