yawad
yawad

Reputation: 143

How to access the jwt token in load function in svelte kit?

I have stored the JWT token in the session storage. But to protect any route, I will need that token. So, how can I access it on the load function provided by the svelte kit which runs on the server ?

Upvotes: 2

Views: 2025

Answers (1)

Stephane Vanraes
Stephane Vanraes

Reputation: 16411

You would use a combination of the handle and getSession hooks for this.

In handle you have access to the cookies of the request, here you can parse them and add them to the request. Later in getSession you use this to fill up the session.

export async function handle({ request, resolve }) {
    request.locals.token= await getToken(request.headers.cookie);
    const response = await resolve(request);
    return response
}
export function getSession(request) {
    return {
      token: request.locals.token ?? ''
    }
}

This session object is available as one of the parameters in the load functions.

export async function load({ session }) {
  const { token } = session
}

In most cases you will parse the token in your handle function to get the data that is stored in it out and pass that on to the rest of the application.

Upvotes: 3

Related Questions