Skip to content

Commit 6289d31

Browse files
committed
1.8.1 Fix server-side route protection
1 parent 45e0c36 commit 6289d31

3 files changed

Lines changed: 19 additions & 3 deletions

File tree

src/lib/auth/AuthContext.tsx

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
import { createContext, FunctionComponent, useState, useEffect } from 'react'
1+
import { createContext, FunctionComponent, useState, useEffect, useCallback } from 'react'
22
import Router from 'next/router'
3-
import { User } from '@supabase/supabase-js'
3+
import { User, Session, AuthChangeEvent } from '@supabase/supabase-js'
44
import { supabase } from '~/lib/supabase'
55
import { useMessage } from '~/lib/message'
66
import { SupabaseAuthPayload } from './auth.types'
@@ -61,6 +61,15 @@ export const AuthProvider: FunctionComponent = ({
6161
}
6262

6363
const signOut = async () => await supabase.auth.signOut()
64+
65+
const setServerSession = async (event: AuthChangeEvent, session: Session) => {
66+
await fetch('/api/auth', {
67+
method: 'POST',
68+
headers: new Headers({ 'Content-Type': 'application/json' }),
69+
credentials: 'same-origin',
70+
body: JSON.stringify({ event, session }),
71+
})
72+
}
6473

6574
useEffect(() => {
6675
const user = supabase.auth.user()
@@ -78,6 +87,7 @@ export const AuthProvider: FunctionComponent = ({
7887
async (event, session) => {
7988
const user = session?.user! ?? null
8089
setUserLoading(false)
90+
await setServerSession(event, session)
8191
if (user) {
8292
setUser(user)
8393
setLoggedin(true)

src/pages/api/auth.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import { NextApiRequest, NextApiResponse} from 'next'
2+
import { supabase } from '~/lib/supabase'
3+
4+
export default function handler(req: NextApiRequest , res: NextApiResponse) {
5+
supabase.auth.api.setAuthCookie(req, res)
6+
}

src/pages/profile.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ const ProfilePage = ({ }: InferGetServerSidePropsType<typeof getServerSideProps>
3636
}
3737

3838
export default ProfilePage
39-
39+
// Fetch user data server-side to eliminate a flash of unauthenticated content.
4040
export const getServerSideProps: GetServerSideProps = async ({ req }): Promise<NextAppPageServerSideProps> => {
4141
const { user } = await supabase.auth.api.getUserByCookie(req)
4242
// We can do a re-direction from the server

0 commit comments

Comments
 (0)