As it turns out, I was doing this kind of wrong. I should have been using a hooks.server.ts
file first of all. Hyntabyte explains it well in this YouTube video: https://www.youtube.com/watch?v=K1Tya6ovVOI
Essentially, we should be doing the auth check in the hooks.server.ts
file, then passing whether or not it is authenticated using Locals. That way, you can access it through locals in each +page.server.ts
file to determine if the user is authenticated or not.
Another issue I was running into later was that I needed to forward to cookies to SvelteKit. I keep trying to set it using event.cookies
, but it should have been event.request.headers.get
like this:
import type { Handle } from '@sveltejs/kit';
import { API_URL } from '$lib/config';
export const handle: Handle = async ({ event, resolve }) => {
const cookies = event.request.headers.get('cookie') || '';
const response = await fetch(`${API_URL}/api/auth/status`, { # my endpoint for checking auth status
credentials: 'include',
headers: {
'X-Requested-With': 'XMLHttpRequest',
Cookie: cookies
}
});
const data = await response.json();
event.locals.isAuthenticated = data.isAuthenticated;
event.locals.user = data.user;
return resolve(event);
};
Finally, I also had issues with CORS. I needed to run my Django server using python manage.py runserver localhost:8000
to prevent it from defaulting to 127.0.0.1:8000
. I also needed to have these in my settings.py
file:
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SAMESITE = 'None'
SESSION_COOKIE_SAMESITE = 'None'