I have a bit of a problem with my client only app. The app works as intended during dev but the built bundle does not work as expected.
Here is where I think my problem is coming from.
I have hooks.js
with the following code:
export const handle = async ({ event, resolve }) => {
const authCookie = event.cookies.get('authCookie');
if (event.url.pathname.startsWith('/app')) {
if (typeof authCookie === 'undefined') {
return new Response(null, {
status: 302,
headers: {
location: '/login'
}
});
}
try {
const userData = JSON.parse(decodeURIComponent(authCookie));
event.locals.user = userData;
return await resolve(event, {});
} catch (err) {
return new Response(null, {
status: 302,
headers: {
location: '/login'
}
});
}
}
return await resolve(event, {});
};
the authCookie
is set in the login
route once a user logs in.
The problem is that when I browse the built bundle, I can successfully login and the cookie seems to be set but when I refresh the page, I get redirected to the login page.
What could be causing this issue and how can make my auth guard work in the statically built bundle?
handle
is a server hook, it does not run on the client and thus cannot work with a static site at all. (Note that vite preview
is not accurate and will still execute it.)
If you want to check cookies and redirect on the client, you could do so in a load
function, e.g. at the layout root (src/routes/+layout.js
). Note that you can only access cookies that have been set with HttpOnly
being false; they are available via the document.cookie
property. This is generally not recommended because if untrusted JS ends up running on the site, it could steal those cookies.