Eric Echemane
Eric Echemane

Reputation: 171

Redirecting from exported handle hook in sveltekit

I have a sveltekit app and I want to check if the user has an accesstoken from the cookie. I can access it through event.request.headers.get('cookie'); and redirects them to a certain route but I can't find specific syntax from the sveltekit docs.

src/hooks.ts

export async function handle({ event, resolve }) {

    const reqCookie = event.request.headers.get('cookie');
    const cookieName = 'userid';
    const keeperCookie = reqCookie.split(';')
        .find((c: string) => c.trim().startsWith(cookieName));

    const response = await resolve(event);

    if (!reqCookie || !keeperCookie) {
        return response.headers.set('location', '/create');
    }

    return response.headers.set('location', '/login');
}

Redirect doesn't work for me and gives me an error in the console enter image description here

Upvotes: 8

Views: 6703

Answers (2)

FrakyDale
FrakyDale

Reputation: 727

return new Response('Redirect', {status: 303, headers: { Location: '/login' }});

So you don't need the base url :)

Upvotes: 14

Eric Echemane
Eric Echemane

Reputation: 171

I just got it using native Response

`return Response.redirect(baseUrl+"/login", 303);`

Upvotes: 8

Related Questions