Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

In this lesson, we will focus on implementing authentication, which is a crucial aspect for our client. Our objectives are as follows:

  • Upon successful registration, the client will save the token to the local storage.
  • When the logout button is pressed while the user is logged in, the access token will be removed, and the user will be redirected to the login template. We will implement the login page itself in the next lesson.
  • The navigation links will be displayed or hidden based on the user's login status.
  • If a request fails with a 401 Unauthenticated response, the user will be redirected to the login page.

Auth register

Auth logout

  1. Create a new dummy component src/views/auth/Login.jsx...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

M
maxralph01 ✓ Link copied!

Hi Povilas,

I know you always say you are not a frontend person. I am in the same boat as you. I just do not enjoy frontend. On the contrary, I enjoy backend so much.

However, I have this observation on frontend and storing Access Token on the local storage. A JavaScript tutor once said, "if you can store the token anywhere in the browser (like local storage, for instance), it can be retrieved with JavaScript by hackers".

Perhaps, you could consider doing the next tutorial (on your to-do list) you have on frontend, storing the Access Token in state.

Finally, I must say, I have learnt new tips from this tutorial as I was really anticipating it.

Cheers!

DL
David Lun ✓ Link copied!

Hi,

To put it simple there 2 ways of storing tokens.

Local Storage:

  • It is convenient and if you don't have a back-end and you're relying on a third parti API, you can't always ask them to set a specific cookie for your site.
  • Works with APIs that require you to put your access token in the Authorization header.

Cookies:

  • The cookie is not accessible Javascript if you're using httpOnly and secure cookies. That means your cookies cannot be accessed using JavaScript.
  • It's automatically sent in every HTTP request to your server.

Depending on your use case, you might not be able to store your tokens in the cookies. Cookies have a size limit of 4KB. There are scenarios where you can't share cookies with your API server or the API requires you to put the access token in the Authorization header. In this case you won't be able to use cookies to store your tokens.

However while httpOnly cookies are not accessible using JavaScript, this doesn't mean that by using cookies, you're safe from XSS attacks involving your access token.

If an attacker can run JavaScript in your application, then they can just send an HTTP request to your server and that will automatically include your cookies. It's just less convenient for the attacker because they can't read the content of the token although they rarely have to. It might also be more advantageous for the attacker to attack using citim's browser rather that using the attacker's machine.

  • Both localStorage and cookies are vulnerable to XSS attacks but it's harder for the attacker to do the attack when you're using httpOnly cookies.

So it depends on your app implementation if you allow someone remotely execute code on a client machine using XSS.

Implementing your own cookie authentication might be not a trivial task.

Laravel Sanctum provides 2 ways of authenticating your application, one of them is using API Tokens which we chose as an auth option for this course.

Another option Laravel Sanctum provides is cookie based stateful sessions to your API endpoints, and we have a tutorial for that too: https://laraveldaily.com/post/laravel-api-auth-vue-sanctum-examples

M
maxralph01 ✓ Link copied!

Thank you for the clarification. The tutor also mentioned the httpOnly. I will do more research on this subject of tokens.

A
augusto-dmh ✓ Link copied!

Advice for JS developers: instead of relying on a third-party library to do something simple such as manipulating local storage with state variables for each item, it is not difficult to write such code in your own application - or even copy paste from an open-source library - instead of importing a whole dependency that you're probably not going to use completely.

Here's a free example:

import { useState } from "react";

export default function useLocalStorage(key, initialValue) {
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const existingValue = window.localStorage.getItem(key);
      return existingValue ? JSON.parse(existingValue) : initialValue;
    } catch (error) {
      console.error(error);
      return initialValue;
    }
  });

  function setValue(newValue) {
    try {
      setStoredValue(newValue);
      window.localStorage.setItem(key, JSON.stringify(newValue));
    } catch (error) {
      console.error(error);
    }
  }

  function removeValue() {
    try {
      setStoredValue(initialValue);
      window.localStorage.removeItem(key);
    } catch (error) {
        console.error(error);
    }
  }

  return [storedValue, setValue, removeValue];
}

A
augusto-dmh ✓ Link copied!

There's a little problem with part of the code provided: not all errors returned by an API have http status code - e.g: network errors -, so using error.response.status with the API out-of-air would result in an error of trying to access a property from undefined.

To fix this, the optional chaining operator - recent in new EcmaScript updates - should be applied: error.response?.status.