javascriptsveltekitnext-auth

sveltekit hooks.server handle has the same name as authjs handle for sveltekit. How do you use both in the same file?


I'm using authjs for authentication in a sveltekit app.

hooks.server.ts has a function called handle() :

export async function handle({ event, resolve }) {
        
    const response = await resolve(event);
    return response;
}

Authjs authentication also use handle property for sveltekit authentication, SvelteKitAuth() has a property called handle :

export const { handle } = SvelteKitAuth({
    providers: [github({clientId: GITHUB_ID, clientSecret: GITHUB_SECRET})
    ],
   ...rest of code
})

I get the session in +layout.server.ts using load function and locals:

export const load = async (event) => {

    return { 
        session : await event.locals.auth() 
    };


}

Currently, I have the authjs code in a separate file auth.ts and export the handle from auth/sveltekit but I would like to have it executed in hooks.server.ts so I can interact with a db

I can't change the names. How do I use both in the hooks.server.ts?


Solution

  • Not 100% sure about your question, but you could import { handle as authHandle } from 'path/to/auth'

    and then you might want to use a sequence to handle what you need.

    Below an example of my setup which is pretty similar.

    hooks.server.ts

    import { sequence } from '@sveltejs/kit/hooks'
    import { handle as authenticationHandle } from './auth'
    
    async function authorizationHandle({ event, resolve }) {
    //protect all routes
    const session = await event.locals.auth();
    
    if (!session && !event.url.pathname.startsWith('/signin')) {
        throw redirect(303, '/signin');
    }
    return resolve(event);
    }
    
    export const handle: Handle = sequence(authenticationHandle, authorizationHandle,  handleParaglide);