skip to Main Content

I want to connect React with Laravel through HTTP-only cookies so that I don’t have to pass the token every time. How can I do that?

I currently have to store this token in local storage, but I don’t want to keep it there. What is the most secure way to store the token?

2

Answers


  1. Chosen as BEST ANSWER

    this one works great

    return response()->json(['message' => 'Logged in successfully']) ->cookie('access_token', $token, $expiration, '/', null, true, true, false);

    whats the most secure way to pass tokens?


  2. I need more details on how you’re building the app to help you with this, but assuming you’re using Laravel’s default native React integration with Inertia, cookies are automatically working without you needing to do anything.

    If you’re accessing API endpoints, then you will need to use tokens, in that case you can set the token on the axios instance once after retrieving the token like so:

    window.axios.defaults.headers.common.Authorization = `Bearer ${res.token}`
    

    This will work until user closes the window.

    You should not store the token in local storage anyway, because it is accessible by JS and vulnerable to XSS attacks.

    Alternatively you can use cookies to store the token:

    return response()->json(['message' => 'Logged in successfully'])
        ->cookie('access_token', $token, $expiration, '/', null, true, true, false);
    

    A more secure option would be using a refresh token stored in cookies and using that to get a new token when the old one is expired.

    If you’re using cookies, make sure they are HTTP-only, Secure, and have a proper SameSite policy.

    Again, default Laravel / React implementation does not require token based authentication.
    You only need tokens if you’re creating a SPA and accessing API end points.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search