-
Notifications
You must be signed in to change notification settings - Fork 27k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
examples: Updates with-supertokens example app (#58525)
Co-authored-by: Lee Robinson <me@leerob.io>
- Loading branch information
1 parent
42b8789
commit 484efae
Showing
49 changed files
with
969 additions
and
652 deletions.
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
import { getAppDirRequestHandler } from 'supertokens-node/nextjs' | ||
import { NextRequest, NextResponse } from 'next/server' | ||
import { ensureSuperTokensInit } from '../../../config/backend' | ||
|
||
ensureSuperTokensInit() | ||
|
||
const handleCall = getAppDirRequestHandler(NextResponse) | ||
|
||
export async function GET(request: NextRequest) { | ||
const res = await handleCall(request) | ||
if (!res.headers.has('Cache-Control')) { | ||
// This is needed for production deployments with Vercel | ||
res.headers.set( | ||
'Cache-Control', | ||
'no-cache, no-store, max-age=0, must-revalidate' | ||
) | ||
} | ||
return res | ||
} | ||
|
||
export async function POST(request: NextRequest) { | ||
return handleCall(request) | ||
} | ||
|
||
export async function DELETE(request: NextRequest) { | ||
return handleCall(request) | ||
} | ||
|
||
export async function PUT(request: NextRequest) { | ||
return handleCall(request) | ||
} | ||
|
||
export async function PATCH(request: NextRequest) { | ||
return handleCall(request) | ||
} | ||
|
||
export async function HEAD(request: NextRequest) { | ||
return handleCall(request) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
import { NextResponse, NextRequest } from 'next/server' | ||
import { withSession } from '../../sessionUtils' | ||
|
||
export function GET(request: NextRequest) { | ||
return withSession(request, async (session) => { | ||
if (!session) { | ||
return new NextResponse('Authentication required', { status: 401 }) | ||
} | ||
|
||
return NextResponse.json({ | ||
note: 'Fetch any data from your application for authenticated user after using verifySession middleware', | ||
userId: session.getUserId(), | ||
sessionHandle: session.getHandle(), | ||
accessTokenPayload: session.getAccessTokenPayload(), | ||
}) | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
'use client' | ||
|
||
import { useEffect, useState } from 'react' | ||
import { redirectToAuth } from 'supertokens-auth-react' | ||
import SuperTokens from 'supertokens-auth-react/ui' | ||
import { PreBuiltUIList } from '../../config/frontend' | ||
|
||
export default function Auth() { | ||
// if the user visits a page that is not handled by us (like /auth/random), then we redirect them back to the auth page. | ||
const [loaded, setLoaded] = useState(false) | ||
useEffect(() => { | ||
if (SuperTokens.canHandleRoute(PreBuiltUIList) === false) { | ||
redirectToAuth({ redirectBack: false }) | ||
} else { | ||
setLoaded(true) | ||
} | ||
}, []) | ||
|
||
if (loaded) { | ||
return SuperTokens.getRoutingComponent(PreBuiltUIList) | ||
} | ||
|
||
return null | ||
} |
23 changes: 23 additions & 0 deletions
23
examples/with-supertokens/app/components/callApiButton.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
'use client' | ||
|
||
import Session from 'supertokens-auth-react/recipe/session' | ||
import styles from '../page.module.css' | ||
|
||
export const CallAPIButton = () => { | ||
const fetchUserData = async () => { | ||
const accessToken = await Session.getAccessToken() | ||
const userInfoResponse = await fetch('http://localhost:3000/api/user', { | ||
headers: { | ||
Authorization: 'Bearer ' + accessToken, | ||
}, | ||
}) | ||
|
||
alert(JSON.stringify(await userInfoResponse.json())) | ||
} | ||
|
||
return ( | ||
<div onClick={fetchUserData} className={styles.sessionButton}> | ||
Call API | ||
</div> | ||
) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
import { getSSRSession } from '../sessionUtils' | ||
import { TryRefreshComponent } from './tryRefreshClientComponent' | ||
import styles from '../page.module.css' | ||
import { redirect } from 'next/navigation' | ||
import Image from 'next/image' | ||
import { CelebrateIcon, SeparatorLine } from '../../assets/images' | ||
import { CallAPIButton } from './callApiButton' | ||
import { LinksComponent } from './linksComponent' | ||
import { SessionAuthForNextJS } from './sessionAuthForNextJS' | ||
|
||
export async function HomePage() { | ||
const { session, hasToken, hasInvalidClaims } = await getSSRSession() | ||
|
||
if (!session) { | ||
if (!hasToken) { | ||
/** | ||
* This means that the user is not logged in. If you want to display some other UI in this | ||
* case, you can do so here. | ||
*/ | ||
return redirect('/auth') | ||
} | ||
|
||
if (hasInvalidClaims) { | ||
return <SessionAuthForNextJS /> | ||
} else { | ||
return <TryRefreshComponent /> | ||
} | ||
} | ||
|
||
return ( | ||
<SessionAuthForNextJS> | ||
<div className={styles.homeContainer}> | ||
<div className={styles.mainContainer}> | ||
<div | ||
className={`${styles.topBand} ${styles.successTitle} ${styles.bold500}`} | ||
> | ||
<Image | ||
src={CelebrateIcon} | ||
alt="Login successful" | ||
className={styles.successIcon} | ||
/>{' '} | ||
Login successful | ||
</div> | ||
<div className={styles.innerContent}> | ||
<div>Your userID is:</div> | ||
<div className={`${styles.truncate} ${styles.userId}`}> | ||
{session.getUserId()} | ||
</div> | ||
<CallAPIButton /> | ||
</div> | ||
</div> | ||
<LinksComponent /> | ||
<Image | ||
className={styles.separatorLine} | ||
src={SeparatorLine} | ||
alt="separator" | ||
/> | ||
</div> | ||
</SessionAuthForNextJS> | ||
) | ||
} |
80 changes: 80 additions & 0 deletions
80
examples/with-supertokens/app/components/linksComponent.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
'use client' | ||
import styles from '../page.module.css' | ||
import { BlogsIcon, GuideIcon, SignOutIcon } from '../../assets/images' | ||
import { recipeDetails } from '../config/frontend' | ||
import Link from 'next/link' | ||
import Image from 'next/image' | ||
import Session from 'supertokens-auth-react/recipe/session' | ||
import SuperTokens from 'supertokens-auth-react' | ||
|
||
const SignOutLink = (props: { name: string; link: string; icon: string }) => { | ||
return ( | ||
<div | ||
className={styles.linksContainerLink} | ||
onClick={async () => { | ||
await Session.signOut() | ||
SuperTokens.redirectToAuth() | ||
}} | ||
> | ||
<Image className={styles.linkIcon} src={props.icon} alt={props.name} /> | ||
<div role={'button'}>{props.name}</div> | ||
</div> | ||
) | ||
} | ||
|
||
export const LinksComponent = () => { | ||
const links: { | ||
name: string | ||
link: string | ||
icon: string | ||
}[] = [ | ||
{ | ||
name: 'Blogs', | ||
link: 'https://supertokens.com/blog', | ||
icon: BlogsIcon, | ||
}, | ||
{ | ||
name: 'Guides', | ||
link: recipeDetails.docsLink, | ||
icon: GuideIcon, | ||
}, | ||
{ | ||
name: 'Sign Out', | ||
link: '', | ||
icon: SignOutIcon, | ||
}, | ||
] | ||
|
||
return ( | ||
<div className={styles.bottomLinksContainer}> | ||
{links.map((link) => { | ||
if (link.name === 'Sign Out') { | ||
return ( | ||
<SignOutLink | ||
name={link.name} | ||
link={link.link} | ||
icon={link.icon} | ||
key={link.name} | ||
/> | ||
) | ||
} | ||
|
||
return ( | ||
<Link | ||
href={link.link} | ||
className={styles.linksContainerLink} | ||
key={link.name} | ||
target="_blank" | ||
> | ||
<Image | ||
className={styles.linkIcon} | ||
src={link.icon} | ||
alt={link.name} | ||
/> | ||
<div role={'button'}>{link.name}</div> | ||
</Link> | ||
) | ||
})} | ||
</div> | ||
) | ||
} |
19 changes: 19 additions & 0 deletions
19
examples/with-supertokens/app/components/sessionAuthForNextJS.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
'use client' | ||
|
||
import React, { useState, useEffect } from 'react' | ||
import { SessionAuth } from 'supertokens-auth-react/recipe/session' | ||
|
||
type Props = Parameters<typeof SessionAuth>[0] & { | ||
children?: React.ReactNode | undefined | ||
} | ||
|
||
export const SessionAuthForNextJS = (props: Props) => { | ||
const [loaded, setLoaded] = useState(false) | ||
useEffect(() => { | ||
setLoaded(true) | ||
}, []) | ||
if (!loaded) { | ||
return props.children | ||
} | ||
return <SessionAuth {...props}>{props.children}</SessionAuth> | ||
} |
19 changes: 19 additions & 0 deletions
19
examples/with-supertokens/app/components/supertokensProvider.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
'use client' | ||
import React from 'react' | ||
import { SuperTokensWrapper } from 'supertokens-auth-react' | ||
import SuperTokensReact from 'supertokens-auth-react' | ||
import { frontendConfig, setRouter } from '../config/frontend' | ||
import { usePathname, useRouter } from 'next/navigation' | ||
|
||
if (typeof window !== 'undefined') { | ||
// we only want to call this init function on the frontend, so we check typeof window !== 'undefined' | ||
SuperTokensReact.init(frontendConfig()) | ||
} | ||
|
||
export const SuperTokensProvider: React.FC<React.PropsWithChildren<{}>> = ({ | ||
children, | ||
}) => { | ||
setRouter(useRouter(), usePathname() || window.location.pathname) | ||
|
||
return <SuperTokensWrapper>{children}</SuperTokensWrapper> | ||
} |
31 changes: 31 additions & 0 deletions
31
examples/with-supertokens/app/components/tryRefreshClientComponent.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
'use client' | ||
|
||
import { useEffect, useState } from 'react' | ||
import { useRouter } from 'next/navigation' | ||
import Session from 'supertokens-auth-react/recipe/session' | ||
import SuperTokens from 'supertokens-auth-react' | ||
|
||
export const TryRefreshComponent = () => { | ||
const router = useRouter() | ||
const [didError, setDidError] = useState(false) | ||
|
||
useEffect(() => { | ||
void Session.attemptRefreshingSession() | ||
.then((hasSession) => { | ||
if (hasSession) { | ||
router.refresh() | ||
} else { | ||
SuperTokens.redirectToAuth() | ||
} | ||
}) | ||
.catch(() => { | ||
setDidError(true) | ||
}) | ||
}, [router]) | ||
|
||
if (didError) { | ||
return <div>Something went wrong, please reload the page</div> | ||
} | ||
|
||
return <div>Loading...</div> | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
export const appInfo = { | ||
appName: 'SuperTokens Next.js demo app', | ||
apiDomain: 'http://localhost:3000', | ||
websiteDomain: 'http://localhost:3000', | ||
apiBasePath: '/api/auth', | ||
websiteBasePath: '/auth', | ||
} |
Oops, something went wrong.