supabase / auth-helpers

A collection of framework specific Auth utilities for working with Supabase.
https://supabase.github.io/auth-helpers/
MIT License
902 stars 237 forks source link

Cookie not set in Chrome with @supabase/auth-helpers-nextjs #694

Closed tomelliot closed 8 months ago

tomelliot commented 10 months ago

Bug report

Describe the bug

In Chrome the Network response shows both Set Cookie headers:

image

The "Cookies" tab for the request shows only one of the cookies:

image

The Cookies for the localhost domain don't contain either of the sb-... cookies

To Reproduce

I'm working on a minimal reproduction

Expected behavior

Session to persist on both Chrome and Firefox.

Additional context

Chrome version 118.0.5993.96 (Official Build) (arm64)

 npm list | grep supabase
├── @supabase/auth-helpers-nextjs@0.8.7
├── @supabase/supabase-js@2.38.0
├── supabase@1.112.0

Same question on Discord (so far unanswered)

tomelliot commented 10 months ago

Workaround:

  1. Use the supabase-js createClient instead of @supabase/auth-helpers-nextjs
  2. Use custom storage handlers
import { SupabaseClient, createClient } from '@supabase/supabase-js';
import { deleteCookie, getCookie, setCookie } from 'cookies-next';

supabase:SupabaseClient = createClient<Database>(
    process.env.NEXT_PUBLIC_SUPABASE_URL,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
    {
      auth: {
        storage: {
          getItem(key) {
            return getCookie(key) || null;
          },
          setItem(key, value) {
            return setCookie(key, value, {
              httpOnly: false,
              sameSite: 'none',
              maxAge: Date.now() + 1000 * 60 * 60 * 24 * 365,
              expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
              secure: typeof document !== 'undefined' && (document.location?.protocol === 'https' || document.location?.hostname === 'localhost'),
            });
          },
          removeItem(key) {
            return deleteCookie(key, { sameSite: 'none', secure: true });
          },
        },
      },
    },
  );

Note that this is setting sameSite to none which is unsafe.

Modified from https://github.com/supabase/auth-helpers/issues/437#issuecomment-1409290489

dijonmusters commented 8 months ago

Thanks for lodging an issue - sorry for the delay in getting back to you!

The auth-helpers and ssr packages are only required to store the session in a cookie making it available serverside. If everything is static with Supabase Auth only being used client-side, using @supabase/supabase-js is the right way to go 👍

You shouldn't need to override the default storage behaviour, as localStorage will be available client-side. This should be fine 👇

import { createClient } from '@supabase/supabase-js';

const supabase = createClient<Database>(
    process.env.NEXT_PUBLIC_SUPABASE_URL,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
  );