In this blog post, we are going to see how can we send multiple cookies to the browser in a Remix powered web app.
Problem Statement
Let us consider the login
functionality in a web app. Once the user is successfully authenticated, we want to --
- Redirect users to their respective dashboard
- Set the session cookie
- Set the tracking cookie
Setting up Session and Redirection
We can use Remix's inbuilt utilities to manage the session and redirect.
import { createCookieSessionStorage, redirect } from "remix";
const storage = createCookieSessionStorage({ ... });
export async function createUserSession(userId) {
const session = await storage.getSession();
session.set("userId", userId);
return redirect('/dashboard');
}
In the function createUserSession
, we get the session, set the userId
, and redirect the user to the dashboard route.
Setting Cookies
- The HTTP helper
redirect
provided by Remix takes an object as the second parameter where we can set different options likestatus
,headers
, and so on. Let us use that to send theSet-Cookie
header with the session cookie as the value.
...
return redirect('/dashboard', {
headers: {
'Set-Cookie': await storage.commitSession(session)
}
});
We are now redirecting the user to the dashboard and also setting the session
cookie to keep them logged in.
- Now, we want to set the tracking cookie. We can try doing the same thing as the session cookie and set another
Set-Cookie
header.
...
return redirect('/dashboard', {
headers: {
'Set-Cookie': await storage.commitSession(session),
'Set-Cookie': 'user_tracking_id=e8bb43229de9; Max-Age=2592000; Path=/; Secure; SameSite=Lax'
}
});
However, the above code snippet introduces a new problem. The most recent Set-Cookie
key would overwrite the previous ones.
Resolving Same Header Key Issue
We can resolve the above-mentioned problem by using the Headers() constructor. We can create a new instance of the Headers object, append keys to it, and send it to the client.
...
const headers = new Headers();
headers.append("Set-Cookie", await storage.commitSession(session));
headers.append('Set-Cookie': 'user_tracking_id=e8bb43229de9; Max-Age=2592000; Path=/; Secure; SameSite=Lax');
return redirect('/dashboard', {
headers,
});
This resolves our problem and both cookies would be stored in the user browser! 🙌
I hope this blog post helped you in some way. Please do share it and show our content much-needed love! 😄
If you feel something is missing/wrong/improvement is possible then feel free to reach out -- Devtools Tech and Yomesh Gupta