node.jscookiesjwtresthttpcookie

How to send http only cookies(containing jwt) with every request in decoupled frontend and backend?


How to send http only cookies with every request in decoupled frontend and backend? My frontend and backend are deployed through heroku , frontend is here :- https://chatapp-client-12345.herokuapp.com/

backend is here :- https://chatappbackend12345.herokuapp.com/

I want to send my http only cookie(containing jwt) to my backend with every request that I set with my backend like this :-

// generate jwt
    let jwtToken = jwt.sign({
        email:email,
        userId:userData._id
    },"somesupersecret");
    res.cookie("jwtToken",jwtToken,{
        expires:new Date(Date.now() + 3600000),
        httpOnly:true,
        domain:"chatapp-client-12345.herokuapp.com"
    });

but the http only cookie is not set in the frontend

Through my research I came to know that I can only access cookie on same domain , but what should I do if my frontend and backend are decoupled?

my backend is based on node js built with rest apis and frontend containing simple html css js served with node js


Solution

  • Assuming your domain is https://chatappbackend12345.herokuapp.com/, you could only set cookies on two domains:

    (1) Exact domain and sub-domain:

    chatappbackend12345.herokuapp.com

    (2) Root domain:

    .herokuapp.com

    For your case, the domain of your frontend and backend is different, which means the cookies could never be able to access by both side simultaneously.

    It is also not likely (or not feasible) to set the cookies to root domain, because you could hardly trust the cookies from websites not belong to you.

    Domain and decoupling are separated concept. You could have the same domain while the frontend and backend applications remain decoupled.

    One way to achieve it is by reverse proxy (Reference: nginx reverse proxy). You could add a reverse proxy on top of your frontend and backend, routing them to the same domain.

    For instance, under your own domain, you could make your reverse proxy application with following routing policy:

    https://chatappbackend12345.herokuapp.com/login: backend application https://chatappbackend12345.herokuapp.com/* : frontend application

    For the case, cookies could be set in client side by your server, while both applications remain decouple.

    For more information about cookies policy, please check rfc6265.