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.
Note that sb:token
should now be sb-access-token
instead
Good call out! Thanks! 🙌
supabase.auth.session
is being reassigned to a function? In other areas, it's being called as a function. Not understanding this part..supabase.auth.session
is asking for a token_type
and user
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
})
}
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