How To Send Your Token(JWT) To Cookies

JSON Web Tokens

Notes guide :

=> : when we have code.
== explanation code == : when we explain code.
[[ additional info ]] : when we have extra code or extra important informations.
{{ external_res }} : when we have external links (videos , tutoriels) support the topic.
<<!!>>: the error with the solution.

To send our token to the cookies in React we installed a package as the following =>

npm i universal-cookie

{{ external_res }}

https://www.npmjs.com/package/universal-cookie

After that, we created a folder called ‘services’
inside it, we created a file and we call it CookieService{js extension}

Then inside the file, we import Cookie from the package that we already installed =>

import Cookie from ‘universal-cookie’;

== explanation code ==
A cookie is a class that exists inside the ‘universal-cookie’ package

Now we create a new instance from Cookie class and we put it inside a constant element =>

const cookie = new Cookie();

== explanation code ==
We become able to use all accessible methods that exist inside Cookie class

What we will do next is create a new class called CookieService and we will build 3 methods that use Cookie’s(class) methods =>

class CookieService {get(key) {
return cookie.get(key);
}
set(key, value, options){cookie.set(key, value, options);
}
remove(key){
cookie.remove(key);
}
}

== Explanation code ==

We created 3 methods:
-The get is to take the token from the cookies using its name
-The set that makes us able to send data and put it inside cookies (key =’ choose the name of cookies element’,value=’give it a value’ options =‘it contain many options related to the data that you are sending’ )
-The remove method to remove the data from cookies

finally don’t forget to export CookieService class =>

export default new CookieService();
example of the postman with JWT authentication

At this point, we become able to call these methods anywhere in our project so let’s call it inside our SignIn page where we will use set method to take the token(JWT) given via fetching API and put it inside our cookies =>

/* this code is not my whole code I just put the part that we are interested in*/import React, { useState, Fragment, } from ‘react’;
import { Link, useHistory } from ‘react-router-dom’;
import CookieService from ‘../../services/CookieService’;
/* We are importing CookieService to use the available methods*/export default function SignIn() {/* we will put inside state the user inputs*/

const [email, setEmail] = useState(‘’);
const [password, setPassword] = useState(‘’);
/* we will create function that work when we submit using the submit button */

const submit = async (e) => {

/* e here is a variable that represents all events that your elements related to this function could have */

e.preventDefault();

/* preventDefault contains many default things one of them is to block the default refresh of submitting type.*/

let body = new FormData();
/* we create a new form data similar to what we have in postman*/ let email1 = email;
let password1 = password;
body.append(‘email’, email1);
body.append(‘password’, password1);

/*we said that our email and password inside ‘body’ are equal to the state value that we get from the user.*/
try {let res = await fetch(‘http://127.0.0.1:8000/api/auth/login', {
method: ‘post’, body,

});

/* this fetching return to me from laravel a response with 3 elements: the token ( named access_token ),expire_in, token_type */

let result = await res.json();
/* we put the response inside a variable called ‘result’ and your response is in JSON form, await is for making sure that all data is being received and stored inside ’result’ */

if (result.access_token) {
const options = { path: ‘/’ }; /* when we have path equal to ‘/’ it’s mean we need this token to be available in cookies in all pages */ CookieService.set(‘access_token’, result.access_token, options) /* we are sending to cookies the token(JWT) via set method that we create before */ history.push(‘/employee’); // console.log(result); } else {
alert(‘Unauthorized’);
}
}
catch (e) {
alert(e);
}
}return (<Fragment>

<div>

<div action=”” className={classes.login_box}>
<form onSubmit={submit}>
/* above we use build in attribute called onSubmit and inside it we put our function name that we call it when we submit the form */<div> <label className={classes.input_label} htmlFor=”Email”>
<input
required
className={classes.input_place}
type=”email”
name=”email”
placeholder=” Email”
onChange={e => setEmail(e.target.value)}
/* we use onchange to catch any changes to the input field
we said that our event here will include the following value
we are setting the state (value) to our email element that we
declared in the top via setEmail */
/>
</label>
</div>
<div><Button className={classes.lgbtn} type=”submit” >Login</Button></div></form></div></div></Fragment>)
}

Now we should find the token inside our cookies like the following :

The Token inside Cookies

Finished!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store