sveltejs / realworld

SvelteKit implementation of the RealWorld app
https://realworld.svelte.dev
MIT License
2.24k stars 353 forks source link

about get({ locals }) #87

Closed yadoga closed 3 years ago

yadoga commented 3 years ago

Quick question about 'locals' in your endpoints: where are these set? Or are they more of a placeholder for any individual session? Could not seem to find any info about this… thanks!

benmccann commented 3 years ago

https://kit.svelte.dev/docs#hooks-handle

rvrm commented 3 years ago

works for me now with:

export async function handle({ request, render }) {
    const cookies = cookie.parse(request.headers.cookie || '')
    const jwt =
        cookies.jwt && Buffer.from(cookies.jwt, 'base64').toString('utf-8')
    const user = jwt ? JSON.parse(jwt) : null
    request.locals.user = user

    const response = await render(request);

    return response;
}

Should /hooks/index.js better not reflect the handle({ request }) method?

Or would handling be possible via the getSession({ headers }) as in your example and I'm missing something? Thank you

benmccann commented 3 years ago

I just tested and am not seeing any issues

Here are the docs for getSession: https://kit.svelte.dev/docs#hooks-getsession

yadoga commented 3 years ago

Should have mentioned it: Need to access a JWT token from the cookie. So by the docs this would be advised against from within getSession.

Works via handle request, so that was just what I could not wrap my head around coming from the hooks/index.json example. Thanks again!

eriknyk commented 3 years ago

however I don't see handle() setup in the realworld example and it is accessing locals.user however handle() is not present in hooks definitions `https://github.com/sveltejs/realworld/blob/master/src/hooks/index.js``

benmccann commented 3 years ago

Oh yeah. I messed that up. I just pushed a fix in case you want to take another look

yadoga commented 3 years ago

Thank you! Link above needs correction, btw.

yadoga commented 3 years ago

headers keeps returning as 'undefined' for me. My app probably deviates a bit from this repo, but nevertheless leaving the following in case it helps someone:

I'm now getting headers by an async function, via the request object.

export async function handle({ request, resolve }) {
    const cookies = cookie.parse(request.headers.cookie || '');
    const jwt = cookies.jwt && Buffer.from(cookies.jwt, 'base64').toString('utf-8');
    request.locals.user = jwt ? JSON.parse(jwt) : null;

    const response = await resolve(request);
    return response;
}
benmccann commented 3 years ago

I just bumped the version of SvelteKit which uses the new method signature for handle