How to use session in React/Redux Frontend and Rails Backend

Simran Manandhar
3 min readApr 1, 2021

For my latest portfolio project i.e, Petgram(an instagram clone), I used sessions cookies for authentication purpose. In my project, a user can signup/ login and logout. It’s easy while using only in Rails. But, coming up with interaction between the frontend and backend with asynchronous activity, it’s kind of lengthy as well as tricky. Here, I will explain the steps that I did to make authenticity work.

Firstly, I added the bcrypt and cors gems in my gemfile:

gem 'bcrypt', '~> 3.1.7'
gem 'rack-cors'

Then, bundle install in the terminal. After that, I made a session_store.rb file inside the config/initializers folder. And added the following code:

Rails.application.config.session_store :cookie_store, :key => '_petgram'

Here, we can write anything in the key. In my case, I wrote ‘_petgram’ as it is my project name.

Next step was to make the user table and user model where we have to write has_secure_password like so:

class User < ApplicationRecord    
has_secure_password
end

I created the user and session controller as shown below:

I also made helper methods, current_user to find the logged in user and logged_in? to check whether a user is logged in or not in the application controller. This would make the two methods available in all the other controllers.

Now comes the react part. I created the components of forms for signup/login/logout in a same order. For the action part, I wrote the following code:

Here, I have passed in two arguments in the signup action. The main part is the credentials: ‘include’ . This is done in order to make the user params available in our backend. The 2nd argument is used in order to redirect the page to my posts page. The logic here is, after signup, show the home page. In my case it’s the posts page. I did the same for the login/logout action.

For the reducers, i have two cases for login/signup and logout.

export default (state={loggedIn: false, currentUser: {}}, action) => { switch (action.type) {  case 'AUTH_SUCCESS':  return {...state, loggedIn: action.payload.loggedIn, currentUser:   action.payload.currentUser}  case 'LOGOUT':  return {   ...state, loggedIn: false, currentUser: {},  }default: return state; }}

In order to make the connection between the frontend and backend, we also need to add the url in the origins and credentials: true in the cors.rb file inside the config/initializers folder.

Here, my react frontend runs on http://localhost:3001.

These are the important parts that is needed in order to make the login/logout/signup work.

--

--