Skip to content

Commit 45e0c36

Browse files
committed
1.8 Add server-side route protection
1 parent fc5a034 commit 45e0c36

2 files changed

Lines changed: 45 additions & 3 deletions

File tree

src/pages/profile.tsx

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
11
import { useEffect } from 'react'
2+
import { GetServerSideProps, InferGetServerSidePropsType } from 'next'
23
import Link from 'next/link'
34
import Router from 'next/router'
5+
import { supabase } from '~/lib/supabase'
46
import { useAuth } from '~/lib/auth'
57
import Layout from '~/components/Layout'
68
import { SpinnerFullPage } from '~/components/Spinner'
79
import { ROUTE_AUTH } from '~/config'
10+
import { NextAppPageServerSideProps } from '~/types/app'
811

9-
const ProfilePage = ({}) => {
12+
const ProfilePage = ({ }: InferGetServerSidePropsType<typeof getServerSideProps>) => {
1013
const { user, userLoading, signOut, loggedIn } = useAuth()
1114

1215
useEffect(() => {
@@ -32,4 +35,25 @@ const ProfilePage = ({}) => {
3235
)
3336
}
3437

35-
export default ProfilePage
38+
export default ProfilePage
39+
40+
export const getServerSideProps: GetServerSideProps = async ({ req }): Promise<NextAppPageServerSideProps> => {
41+
const { user } = await supabase.auth.api.getUserByCookie(req)
42+
// We can do a re-direction from the server
43+
if(!user) {
44+
return {
45+
redirect: {
46+
destination: '/',
47+
permanent: false,
48+
},
49+
}
50+
}
51+
// or, alternatively, can send the same values that client-side context populates to check on the client and redirect
52+
// The following lines won't be used as we're redirecting above
53+
return {
54+
props: {
55+
user,
56+
loggedIn: !!user
57+
}
58+
}
59+
}

src/types/app.ts

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,25 @@
1+
import { User } from '@supabase/supabase-js'
2+
13
export type NextAppSEOProps = {
24
title: string
35
}
46

57
export type NextAppPageProps = {
68
meta: NextAppSEOProps,
7-
}
9+
}
10+
11+
export type NextAppPageUserProps = {
12+
props: {
13+
user: User,
14+
loggedIn: boolean
15+
}
16+
}
17+
18+
export type NextAppPageRedirProps = {
19+
redirect: {
20+
destination: string,
21+
permanent: boolean
22+
}
23+
}
24+
25+
export type NextAppPageServerSideProps = NextAppPageUserProps | NextAppPageRedirProps

0 commit comments

Comments
 (0)