I deployed my svelte app where in hook.server.js i use jwt token stored in Cookies to verify if user is authenticated but my server there is not cookies in request Event. I mention that i don't have any issue in local. Here is my login where i set token in cookies :
/** @type {import('./$types').Actions} */
export const actions = {
logIn: async ({ cookies, request, locals }) => {
const data = await request.formData();
const username = data.get('username');
const password = data.get('password');
const body = { username, password };
const response = await login(body);
const { user, accessToken } = response;
locals.user = user;
cookies.set('auth', accessToken, { path: '/', sameSite: 'lax' });
locals.token = accessToken;
console.log("testcook", cookies.get('auth'));
throw redirect(303, '/');
},
}
Here is my handle function in hook.server.js
export const handle: Handle = async ({ event, resolve }) => {
console.log("handle hook", event.cookies.get('auth'));
const userToken = event.cookies.get('auth');
/*i take token and call backend to verify validity of token*/
const user = await authenticateUser(userToken);
if (!user && event.url.pathname !== "/login") {
console.log(event.locals.user);
event.locals.user = null;
console.log("redirecting to login")
throw redirect(303, "/login")
}
event.locals.user = user;
event.locals.token = await event.cookies.get('auth');
return resolve(event);
}
After login in server-ip:port/login with good data, my console log in login (console.log("testcook", cookies.get('auth'));) give good result and throw to "/" but console.log("handle hook", event.cookies.get('auth'));
in handle function of hook.server.js is alwayss undefined.
But in localhost i don't have issue.
I try to add domain but n cookies.set('auth', accessToken, { path: '/', sameSite: 'lax' , domain:'ip'});
This is probably due to how you are setting the cookie. I had to play around the cookie options to get it to work. Try these options:
{
path: "/",
httpOnly: true,
sameSite: "none",
secure: true
}