Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A bug with SvelteKit SSR auth protected routes #23315

Closed
2 tasks done
Honzoraptor31415 opened this issue Apr 27, 2024 · 0 comments
Closed
2 tasks done

A bug with SvelteKit SSR auth protected routes #23315

Honzoraptor31415 opened this issue Apr 27, 2024 · 0 comments
Labels
bug Something isn't working

Comments

@Honzoraptor31415
Copy link
Contributor

Bug report: SvelteKit SSR auth protected routes

  • I confirm this is a bug with Supabase, not with my own application.
  • I confirm I have searched the Docs, GitHub Discussions, and Discord.

Describe the bug

When using SvelteKit server hooks: src/hooks.server.ts and trying to protect some of my routes using code from the docs, the hook seems to never actually get the current session or user and always thinks that both are null, even when logged in.

To Reproduce

  1. Create a new SvelteKit app:
npm create svelte@latest
  1. Install deps:
npm i @supabase/supabase-js @supabase/ssr
  1. Make a basic project structure with a login route (/auth), a protected route (/private) and signing in functionality
  2. Make the server hook:
    hooks.server.ts:
// All of this code is copied from supabase's official docs

import { createServerClient } from '@supabase/ssr'
import { type Handle, redirect } from '@sveltejs/kit'
import { sequence } from '@sveltejs/kit/hooks'

import { PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY } from '$env/static/public'

const supabase: Handle = async ({ event, resolve }) => {
  /**
   * Creates a Supabase client specific to this server request.
   *
   * The Supabase client gets the Auth token from the request cookies.
   */
  event.locals.supabase = createServerClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY, {
    cookies: {
      get: (key) => event.cookies.get(key),
      /**
       * SvelteKit's cookies API requires `path` to be explicitly set in
       * the cookie options. Setting `path` to `/` replicates previous/
       * standard behavior.
       */
      set: (key, value, options) => {
        event.cookies.set(key, value, { ...options, path: '/' })
      },
      remove: (key, options) => {
        event.cookies.delete(key, { ...options, path: '/' })
      },
    },
  })

  /**
   * Unlike `supabase.auth.getSession()`, which returns the session _without_
   * validating the JWT, this function also calls `getUser()` to validate the
   * JWT before returning the session.
   */
  event.locals.safeGetSession = async () => {
    const {
      data: { session },
    } = await event.locals.supabase.auth.getSession()
    if (!session) {
      return { session: null, user: null }
    }

    const {
      data: { user },
      error,
    } = await event.locals.supabase.auth.getUser()
    if (error) {
      // JWT validation has failed
      return { session: null, user: null }
    }

    return { session, user }
  }

  return resolve(event, {
    filterSerializedResponseHeaders(name) {
      /**
       * Supabase libraries use the `content-range` header, so we need to
       * tell SvelteKit to pass it through.
       */
      return name === 'content-range'
    },
  })
}

const authGuard: Handle = async ({ event, resolve }) => {
  const { session, user } = await event.locals.safeGetSession()
  event.locals.session = session
  event.locals.user = user

  if (!event.locals.session && event.url.pathname.startsWith('/private')) {
    return redirect(303, '/auth')
  }

  if (event.locals.session && event.url.pathname === '/auth') {
    return redirect(303, '/private')
  }

  return resolve(event)
}

export const handle: Handle = sequence(supabase, authGuard)

Expected behavior

The supabase ssr client should redirect me to /auth if I'm not logged in and try to access the /private and redirect me to /private when I am logged and try to access /auth.

System information

  • OS: Windows
  • Browser: chrome
  • Version of supabase-js: 2.39.7
  • Version of ssr: 0.3.0
  • Version of Node.js: 21.1.0
  • Version of SvelteKit: 2.5.2

Also

I'm not shure if this is just some bad code in the SvelteKit SSR docs or if it's a problem with the source code itself.

@Honzoraptor31415 Honzoraptor31415 added the bug Something isn't working label Apr 27, 2024
@Honzoraptor31415 Honzoraptor31415 closed this as not planned Won't fix, can't repro, duplicate, stale Apr 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant