1. 19
    Pass Supabase Session Cookie to API Route to Identify User
    4m 16s

Pass Supabase Session Cookie to API Route to Identify User

Share this video with your friends

Send Tweet

Supabase does not automatically set an auth cookie for our signed-in user. If we want to know who our user is on the server, we need to call supabase.auth.api.setAuthCookie.

We will create an API route to set a Supabase auth cookie. Additionally, we modify our useUser hook to call this endpoint anytime the state of our user changes. In order to make our HTTP requests slightly more readable, we install the axios library.

Now that we have a cookie being automatically sent with every request, we can use the getUserByCookie function to get the requesting user. If our API route requires a signed-in user, we can immediately send a 401 response if a user is not present.

We need to know our user's stripe_customer to initiate a checkout session with Stripe (next lesson), so need to enrich this user data with their profile.

While our request from the client to the API route contains our auth cookie, it is not automatically attached to server-side calls using our Supabase client.

~ 2 years ago

Note that sb:token should now be sb-access-token instead

Jon Meyers
Jon Meyers(instructor)
~ 2 years ago

Good call out! Thanks! 🙌

George
George
~ 2 years ago
  1. What is the reason supabase.auth.session is being reassigned to a function? In other areas, it's being called as a function. Not understanding this part..
  2. supabase.auth.session is asking for a token_type and user
~ 2 years ago
  1. Code should look like that, I'm using TS that is why req.headers.cookie && and if (token) is added here
  const token = req.headers.cookie && cookie.parse(req.headers.cookie)['sb-access-token']

  if (token) {
    supabase.auth.session = () => ({
      access_token: token,
      token_type: 'Bearer',
      user
    })
  }
Jon Meyers
Jon Meyers(instructor)
~ 2 years ago

Supabase now exposes a helper function called setAuth for providing a custom access_token. Check out the docs for a full example, but basically we want to replace:

supabase.auth.session = () => ({
    access_token: token,
  });

with:

supabase.auth.setAuth(token)

https://supabase.com/docs/reference/javascript/auth-setauth