1
votes

I am trying to pass an object from endpoint to getSession, which I believe they are all run in server. I can get the value passed with cookie but not those passed with request.locals.<variable>:

src/hooks.ts:

import cookie from 'cookie'

export async function handle({request, resolve}) {
  const cookies = cookie.parse(request.headers.cookie || '')

  request.locals.accessToken = cookies.accessToken
  request.locals.refreshToken = cookies.refreshToken

  const response = await resolve(request)

  const accessToken = `accessToken=${request.locals.accessToken || ''}; Path=/; Secure; HttpOnly;`
  const refreshToken = `refreshToken=${request.locals.refreshToken || ''}; Path=/; Secure; HttpOnly;`

  response.headers['set-cookie'] = [accessToken, refreshToken]
  
  return response
}

export async function getSession(request) {
    console.log('check request local', request.locals)
  return {
    accessToken: request.locals.accessToken,
    refreshToken: request.locals.refreshToken,
    user: request.locals.user
  }
}

My endpoint:

export const post: RequestHandler<Locals, FormData> = async(req) => {
    const name = req.body.get("name")
    const password = req.body.get("password")

    if (!name || !password) {
        return {
            status: 400,
            body: {
                message: "Missing username or password"
            }
        }
    }
    const { access_token, refresh_token } = await getAccessToken(name, password)

  req.locals.accessToken = access_token
  req.locals.refreshToken = refresh_token

    const user = await getUser(access_token)

    req.locals.user = user
  
  return {
    status: 302,
    headers: {
      location: '/lobby'
    }
  }
}

Should I run getUser in handle, if I want to pass data with request.locals to getSession?

Edit

I am actually able to get the value of request.locals.user after const response = await resolve(request), but not before resolve. Why is that?

1
Did you ever solve this issue? Having issues of my own. I don't know how to get the user data obtained in either handle or getSession to my page data. - LaytonGB
Yes I do. The thing is data is being passed around exclusively with cookie. So if you need that, pass it with cookie. - John Winston

1 Answers

2
votes

Getting user information in your hooks.ts's handle() (before const response = await resolve(request) is a good place for it. This is because if you're going to limit access to a page or endpoint based on who the user is (or a user role perhaps), you want that to happen before the page or endpoint are called.

Regarding your other question about why request.locals.user is not populated until after resolving the request, it seems like a bug to me. I can confirm the same behavior. You might want to submit it as an issue.