DEV Community

Shubham Patil
Shubham Patil

Posted on • Originally published at shubhampatilsd.Medium

Storing Login Information With Cookies (JavaScript)

This is an article originally from Medium. I have decided to switch from Medium to dev.to and import all my posts from there.

illustrated person sitting at desk with icons of the technologies covered in the blog surrounding them

Let’s create a hypothetical situation. Say you have important login information for a site you’re building. If we wanted to implement a system where your site would automatically log the user in when they visit, the approach of making the user click the button to login every time will not work.

This is where cookies come into the picture. HTTP Cookies, in simple terms, are a way to store data, which then can be sent to a server. An example in a video by Tom Scott, a cookie can be used for a dark/light mode preference. Your browser would set a cookie containing a preference of which theme to use, and the server would communicate back the correct one. In this tutorial, however, we will be using cookies for storage, not for communicating with a server.

There is an npm package we can use called js-cookie(or, alternatively, you can use a script tag to import it from jsDelivr CDN. Use this link for more info on how to install it.)

Now comes the actual implementation. I’m going to be using React for this (a UI library for JS), but you can use anything that involves JavaScript. From my last writing, I used Firebase Authentication to get login info. I am going to be picking up the code from there (you don’t need to read that one to understand what is going on though). To import js-cookie after installing it, put this line of code at the top of your JavaScript file:

import Cookies from ‘js-cookie’

Now, this is the code to set a cookie after we get the login information: (Login.js)

const loginAsync = async () =>{
        const res = await githubLogin();

        //This is where we create the Cookie. Note the syntax.
        //The JavaScript object we created here is just stuff for me to use later.

        Cookies.set('userInfo', {
            username: res.additionalUserInfo.username,
            pfp: (res.additionalUserInfo.profile.avatar_url).toString()+'.png',
            accessToken: res.credential.accessToken

        }, {expires: 29})

        //The expires line basically says the cookie expires in 29 days.

        //this is not a part of js-cookie but if you're interested, I have a getter and setter with React's useState hook which basically
        //says if it has to redirect to the main content.
        setRedirect(true);   
    }
Enter fullscreen mode Exit fullscreen mode

The res variable is the response from the Firebase Authentication regarding the user’s GitHub account details (I implemented a “Login With Github” button). We set the cookie with Cookies.set(). The first argument the function takes in is the name of the cookie. In this case, I set it to userInfo. The second argument is an object (which resembles JSON). This is the content of the cookie. It doesn’t have to follow this structure and can contain anything as long as it is under 4 kilobytes. You can have up to 50 cookies on your domain as per this Stack Overflow post. The third argument is optional and is another object that defines how long the cookie will last (here, I put it for 29 days).

Now, when the user signs in, we have stored their login credentials in a cookie!

Retrieving this cookie is equally as easy. Now that we have stored the login credentials, you can redirect the user to the main page. If you’re using plain HTML + CSS + JavaScript, you can normally set the window.location.href to the page you want your user to go to. This is a great tutorial to help you setup a server to host your pages. You can also skip ahead as this next section will cover redirecting with React.

If you are using React however, you would use React Router to accomplish this task.

To install the web version of React Router, run npm i react-router-dom in the directory of your project. (Note: Don’t install the package named react-router as it will install the module for React Native, a way to write mobile applications with React.) Great! You now have React Router installed!

Now, you should start coding in the file that contains the ReactDOM.render() function.

import React from 'react';
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';
import ReactDOM from 'react-dom';

import yourComponent from 'RELATIVE_PATH_TO_YOUR_COMPONENT';




ReactDOM.render(


  <Router>
    <Switch>
      <Route path="/PAGE_NAME" component={yourComponent}/>    

    </Switch>
  </Router>
  ,
  document.getElementById('root')
);

Enter fullscreen mode Exit fullscreen mode

Let me break this down. At the top, we have our React Router imports that basically import what we need. The import yourComponent from ‘RELATIVE_PATH_TO_YOUR_COMPONENT’; is more crucial however.

With React Router, instead of pointing to new HTML files, we can load components when we redirect to a certain endpoint. You can rename yourComponent to whatever you want. The RELATIVE_PATH_TO_YOUR_COMPONENT is the path to your component from the JavaScript file that renders our React code.

Now let’s look at this block of code:

<Router>  
    <Switch>  
        <Route path="/PAGE\_NAME" component={yourComponent}/>  
    </Switch>  
</Router>
Enter fullscreen mode Exit fullscreen mode

What this basically does is setup the endpoints for our web application. The <Router> just tells React that “This is the code where we setup the URL endpoints.” The <Switch> is a component that selects the first endpoint if all of them match. For example, if we have an endpoint for /profile and /:variable , (the latter being so that you can retrieve parameters from the URLs of the endpoints such as retrieving the “ShubhamPatilsd” in github.com/ShubhamPatilsd), <Switch> will only use the first endpoint, or in this case, /profile .

The <Route> component is most important of all here. This is what defines the endpoints for our React app. You can see in this example that I’ve set the path to /PAGE_NAME and it renders yourComponent when a user tries to access that page. Change the PAGE_NAME part to the endpoint you want. For example if you wanted /cool , you would change it to /cool instead of /PAGE_NAME .

There are a lot of things that React Router offers and I suggest reading their documentation to get more information.

Now that we’ve setup the infrastructure to handle our links, we can actually talk about how to retrieve the cookies.

To import js-cookie , again, type import Cookies from ‘js-cookie’ at the top of your JavaScript file. Then, to retrieve the data, use this code below:

JSON.parse(Cookies.get('userInfo'));

You’re going to need JSON.parse because js-cookie doesn’t automatically return the cookie data in JSON but instead returns it as a string. That’s an issue because if the rest of your code tries to access the raw string like its JSON, it will result in errors.

If you’re using plain HTML, CSS, and JavaScript, this is the end of the guide! I hope you’ve got cookies working! If not, do look at this video, and if it still doesn’t work, you could write a comment so I can help you.

If you’re using React however, there are still some extra steps that could benefit you in the long-run.

First, import the <Redirect> component from the React Router library by typing this at the top of your JavaScript file:

import {Redirect} from 'react-router-dom';

Then, implement a if-else statement to check if the user is logged in like so:

if(!Cookies.get('userInfo')){
    return <Redirect to='/login'  />
  }else{
      const userData = JSON.parse(Cookies.get('userInfo'));
      //your ui here
Enter fullscreen mode Exit fullscreen mode

For the condition in the first if block, it checks if the cookie by the name of userInfo is null or not. If it is, we redirect the user to a certain endpoint called /login . (Note: You can redirect the user to any endpoint you want, just remember to set it up!). If the cookie is not null however, we store the parsed JSON of the cookie inside a varible called userData.

And that’s it! Now you can access this userData variable like a JSON object!

Thanks for reading my second Medium article! If you have any suggestions, do let me know in a private comment!

By Shubham Patil on April 19, 2021.

Canonical link

Exported from Medium on August 15, 2021.

Top comments (0)