-
Notifications
You must be signed in to change notification settings - Fork 94
feat: Next.js SSR Improvements #877
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 6 commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
0797deb
improv: add an improved way of refreshing the session during SSR
bcbogdan 5bfbbd1
check server actions
bcbogdan 3b1973c
Add authenticate HOF for server actions
bcbogdan 0c1ecca
Update examples
bcbogdan deccb9c
Code review fixes
bcbogdan f781088
Merge branch 'master' into feat/nextjs-ssr
bcbogdan ddcc439
Merge branch '0.50' into feat/nextjs-ssr
bcbogdan 29685a6
fix: Fix token management during ssr in header based setups
bcbogdan bd3c991
test: Add nextjs e2e tests
bcbogdan 77ee188
test: Extend e2e tests
bcbogdan bfa3607
fix: Linting fixes
bcbogdan 4b0cb5d
chore: Update changelog
bcbogdan 955e4cd
fix: Move jwtVerify to a separate file and remove jose
bcbogdan f7dddce
fix: Fix prune errors
bcbogdan 19115da
ci: Update core docker image
bcbogdan fde0f49
chore: Remove comments
bcbogdan f3411f1
fix: Fix exports to make tests work
bcbogdan 7a5630a
test: Update CI testing
bcbogdan 3eaa59d
fix: Code review fixes
bcbogdan 8ae42df
fix: Use the correct path for the refresh token cookie
bcbogdan 1ce9d0b
fix: Update naming to underline lack of claim validation
bcbogdan 99543fb
fix: Include requireAuth in the getServerActionSession function
bcbogdan bbd2287
test: Fix flaky tests
bcbogdan 4d83718
fix: Fix function names
bcbogdan 75048f3
fix: review fixes
porcellus c503a3c
chore: update size limit
porcellus File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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,5 @@ | ||
| NEXT_PUBLIC_SUPERTOKENS_APP_NAME=test | ||
| NEXT_PUBLIC_SUPERTOKENS_API_DOMAIN=http://localhost:3000 | ||
| NEXT_PUBLIC_SUPERTOKENS_WEBSITE_DOMAIN=http://localhost:3000 | ||
| NEXT_PUBLIC_SUPERTOKENS_API_BASE_PATH=/api/auth | ||
| NEXT_PUBLIC_SUPERTOKENS_WEBSITE_BASE_PATH=/auth |
This file contains hidden or 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,3 @@ | ||
| { | ||
| "extends": "next/core-web-vitals" | ||
| } |
This file contains hidden or 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,38 @@ | ||
| # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. | ||
|
|
||
| # dependencies | ||
| /node_modules | ||
| /.pnp | ||
| .pnp.js | ||
|
|
||
| # testing | ||
| /coverage | ||
|
|
||
| # next.js | ||
| /.next/ | ||
| /out/ | ||
|
|
||
| # production | ||
| /build | ||
|
|
||
| # misc | ||
| .DS_Store | ||
| *.pem | ||
|
|
||
| # debug | ||
| npm-debug.log* | ||
| yarn-debug.log* | ||
| yarn-error.log* | ||
|
|
||
| # local env files | ||
| .env*.local | ||
|
|
||
| # vercel | ||
| .vercel | ||
|
|
||
| # typescript | ||
| *.tsbuildinfo | ||
| next-env.d.ts | ||
|
|
||
| # VSCode | ||
| .vscode |
This file contains hidden or 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,42 @@ | ||
| # SuperTokens App with Next.js app directory | ||
|
|
||
| This is a simple application that is protected by SuperTokens. This app uses the Next.js app directory. | ||
|
|
||
| ## How to use | ||
|
|
||
| ### Using `create-next-app` | ||
|
|
||
| - Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example: | ||
|
|
||
| ```bash | ||
| npx create-next-app --example with-supertokens with-supertokens-app | ||
| ``` | ||
|
|
||
| ```bash | ||
| yarn create next-app --example with-supertokens with-supertokens-app | ||
| ``` | ||
|
|
||
| ```bash | ||
| pnpm create next-app --example with-supertokens with-supertokens-app | ||
| ``` | ||
|
|
||
| - Run `yarn install` | ||
|
|
||
| - Run `npm run dev` to start the application on `http://localhost:3000`. | ||
|
|
||
| ### Using `create-supertokens-app` | ||
|
|
||
| - Run the following command | ||
|
|
||
| ```bash | ||
| npx create-supertokens-app@latest --frontend=next | ||
| ``` | ||
|
|
||
| - Select the option to use the app directory | ||
|
|
||
| Follow the instructions after `create-supertokens-app` has finished | ||
|
|
||
| ## Notes | ||
|
|
||
| - To know more about how this app works and to learn how to customise it based on your use cases refer to the [SuperTokens Documentation](https://supertokens.com/docs/guides) | ||
| - We have provided development OAuth keys for the various built-in third party providers in the `/app/config/backend.ts` file. Feel free to use them for development purposes, but **please create your own keys for production use**. |
21 changes: 21 additions & 0 deletions
21
examples/with-next-ssr-app-directory/app/actions/serverActionThatLoadsTheSession.ts
This file contains hidden or 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,21 @@ | ||
| "use server"; | ||
|
|
||
| import { cookies } from "next/headers"; | ||
| import { getServerActionSession, init } from "supertokens-auth-react/nextjs/ssr"; | ||
| import { ssrConfig } from "../config/ssr"; | ||
|
|
||
| init(ssrConfig()); | ||
|
|
||
| export async function serverActionThatLoadsTheSession() { | ||
| const cookiesStore = await cookies(); | ||
| const { status, session } = await getServerActionSession(cookiesStore); | ||
| if (status !== "valid") { | ||
| // User is not authenticated return early or throw an error | ||
| return; | ||
| } | ||
|
|
||
| // Perform the authenticated action | ||
| const userId = session.userId; | ||
| console.log("userId", userId); | ||
| return Promise.resolve(true); | ||
| } |
161 changes: 161 additions & 0 deletions
161
examples/with-next-ssr-app-directory/app/api/auth/[...path]/route.ts
This file contains hidden or 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,161 @@ | ||
| import { getAppDirRequestHandler } from "supertokens-node/nextjs"; | ||
| import Session, { refreshSessionWithoutRequestResponse } from "supertokens-node/recipe/session"; | ||
| import { NextRequest, NextResponse } from "next/server"; | ||
| import { ensureSuperTokensInit } from "../../../config/backend"; | ||
| import { cookies } from "next/headers"; | ||
|
|
||
| ensureSuperTokensInit(); | ||
|
|
||
| const handleCall = getAppDirRequestHandler(); | ||
|
|
||
| // input | ||
| // { refreshSessionWithoutRequestResponse } | ||
| // async function | ||
| // | ||
|
|
||
| export async function GET(request: NextRequest) { | ||
| if (request.method === "GET" && request.url.includes("/session/refresh")) { | ||
| return refreshSession(request); | ||
| } | ||
| 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); | ||
| } | ||
|
|
||
| const refreshTokenCookieName = "sRefreshToken"; | ||
| const refreshTokenHeaderName = "st-refresh-token"; | ||
| async function refreshSession(request: NextRequest) { | ||
| console.log("Attempting session refresh"); | ||
| const cookiesFromReq = await cookies(); | ||
|
|
||
| const refreshToken = | ||
| request.cookies.get(refreshTokenCookieName)?.value || request.headers.get(refreshTokenHeaderName); | ||
| if (!refreshToken) { | ||
| return NextResponse.redirect(new URL("/auth", request.url)); | ||
| } | ||
|
|
||
| const redirectTo = new URL("/", request.url); | ||
|
|
||
| try { | ||
| const refreshResponse = await fetch(`http://localhost:3000/api/auth/session/refresh`, { | ||
| method: "POST", | ||
| headers: { | ||
| "Content-Type": "application/json", | ||
| Cookie: `sRefreshToken=${refreshToken}`, | ||
| }, | ||
| credentials: "include", | ||
| }); | ||
| // console.log("Performed session refresh request"); | ||
| // console.log(refreshResponse); | ||
| // console.log(refreshResponse.headers); | ||
| // console.log(await refreshResponse.text()); | ||
|
|
||
| const setCookieHeaders = refreshResponse.headers.getSetCookie(); | ||
| const frontToken = refreshResponse.headers.get("front-token"); | ||
| if (!frontToken) { | ||
| return NextResponse.redirect(new URL("/auth", request.url)); | ||
| } | ||
|
|
||
| // TODO: Check for csrf token | ||
| if (!setCookieHeaders.length) { | ||
| return NextResponse.redirect(new URL("/auth", request.url)); | ||
| } | ||
|
|
||
| const response = NextResponse.redirect(redirectTo); | ||
| let sAccessToken: string | null = null; | ||
| let sRefreshToken: string | null = null; | ||
| for (const header of setCookieHeaders) { | ||
| if (header.includes("sAccessToken")) { | ||
| const match = header.match(/sAccessToken=([^;]+)/); | ||
| sAccessToken = match ? match[1] : null; | ||
| } | ||
| if (header.includes("sRefreshToken")) { | ||
| const match = header.match(/sRefreshToken=([^;]+)/); | ||
| sRefreshToken = match ? match[1] : null; | ||
| } | ||
| response.headers.append("set-cookie", header); | ||
| } | ||
|
|
||
| response.headers.append("set-cookie", `sFrontToken=${frontToken}`); | ||
| response.headers.append("front-token", frontToken); | ||
| response.headers.append("frontToken", frontToken); | ||
| if (sAccessToken) { | ||
| response.headers.append("sAccessToken", sAccessToken); | ||
|
|
||
| cookiesFromReq.set("sAccessToken", sAccessToken); | ||
| } | ||
| if (sRefreshToken) { | ||
| response.headers.append("sRefreshToken", sRefreshToken); | ||
|
|
||
| cookiesFromReq.set("sRefreshToken", sRefreshToken); | ||
| } | ||
|
|
||
| cookiesFromReq.set("sFrontToken", frontToken); | ||
|
|
||
| // console.log(sAccessToken, sRefreshToken); | ||
|
|
||
| return response; | ||
| } catch (err) { | ||
| console.error("Error refreshing session"); | ||
| console.error(err); | ||
| return NextResponse.redirect(new URL("/auth", request.url)); | ||
| } | ||
| } | ||
|
|
||
| // async function saveTokensFromHeaders(response: Response) { | ||
| // logDebugMessage("saveTokensFromHeaders: Saving updated tokens from the response headers"); | ||
| // | ||
| // const refreshToken = response.headers.get("st-refresh-token"); | ||
| // if (refreshToken !== null) { | ||
| // logDebugMessage("saveTokensFromHeaders: saving new refresh token"); | ||
| // await setToken("refresh", refreshToken); | ||
| // } | ||
| // | ||
| // const accessToken = response.headers.get("st-access-token"); | ||
| // if (accessToken !== null) { | ||
| // logDebugMessage("saveTokensFromHeaders: saving new access token"); | ||
| // await setToken("access", accessToken); | ||
| // } | ||
| // | ||
| // const frontToken = response.headers.get("front-token"); | ||
| // if (frontToken !== null) { | ||
| // logDebugMessage("saveTokensFromHeaders: Setting sFrontToken: " + frontToken); | ||
| // await FrontToken.setItem(frontToken); | ||
| // updateClockSkewUsingFrontToken({ frontToken, responseHeaders: response.headers }); | ||
| // } | ||
| // const antiCsrfToken = response.headers.get("anti-csrf"); | ||
| // if (antiCsrfToken !== null) { | ||
| // // At this point, the session has either been newly created or refreshed. | ||
| // // Thus, there's no need to call getLocalSessionState with tryRefresh: true. | ||
| // // Calling getLocalSessionState with tryRefresh: true will cause a refresh loop | ||
| // // if cookie writes are disabled. | ||
| // const tok = await getLocalSessionState(false); | ||
| // if (tok.status === "EXISTS") { | ||
| // logDebugMessage("saveTokensFromHeaders: Setting anti-csrf token"); | ||
| // await AntiCsrfToken.setItem(tok.lastAccessTokenUpdate, antiCsrfToken); | ||
| // } | ||
| // } | ||
| // } |
23 changes: 23 additions & 0 deletions
23
examples/with-next-ssr-app-directory/app/api/user/route.ts
This file contains hidden or 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 @@ | ||
| import { ensureSuperTokensInit } from "@/app/config/backend"; | ||
| import { NextResponse, NextRequest } from "next/server"; | ||
| import { withSession } from "supertokens-node/nextjs"; | ||
|
|
||
| ensureSuperTokensInit(); | ||
|
|
||
| export function GET(request: NextRequest) { | ||
| return withSession(request, async (err, session) => { | ||
| if (err) { | ||
| return NextResponse.json(err, { status: 500 }); | ||
| } | ||
| 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(), | ||
| }); | ||
| }); | ||
| } |
27 changes: 27 additions & 0 deletions
27
examples/with-next-ssr-app-directory/app/auth/[[...path]]/page.tsx
This file contains hidden or 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,27 @@ | ||
| "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); | ||
|
|
||
| console.log("running this"); | ||
|
|
||
| useEffect(() => { | ||
| if (SuperTokens.canHandleRoute(PreBuiltUIList) === false) { | ||
| redirectToAuth({ redirectBack: false }); | ||
| } else { | ||
| setLoaded(true); | ||
| } | ||
| }, []); | ||
|
|
||
| if (loaded) { | ||
| return SuperTokens.getRoutingComponent(PreBuiltUIList); | ||
| } | ||
|
|
||
| return null; | ||
| } |
17 changes: 17 additions & 0 deletions
17
examples/with-next-ssr-app-directory/app/components/callApiButton.tsx
This file contains hidden or 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 @@ | ||
| "use client"; | ||
|
|
||
| import styles from "../page.module.css"; | ||
|
|
||
| export const CallAPIButton = () => { | ||
| const fetchUserData = async () => { | ||
| const userInfoResponse = await fetch("http://localhost:3000/api/user"); | ||
|
|
||
| alert(JSON.stringify(await userInfoResponse.json())); | ||
| }; | ||
|
|
||
| return ( | ||
| <div onClick={fetchUserData} className={styles.sessionButton}> | ||
| Call API | ||
| </div> | ||
| ); | ||
| }; |
47 changes: 47 additions & 0 deletions
47
examples/with-next-ssr-app-directory/app/components/home.tsx
This file contains hidden or 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,47 @@ | ||
| import { cookies, headers } from "next/headers"; | ||
| 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"; | ||
|
|
||
| import { getServerComponentSession, init } from "supertokens-auth-react/nextjs/ssr"; | ||
| import { ssrConfig } from "../config/ssr"; | ||
| import { useState } from "react"; | ||
| import { MiddlewareServerActionButton } from "./middlewareServerActionButton"; | ||
| import { ServerActionButton } from "./serverActionButton"; | ||
|
|
||
| init(ssrConfig()); | ||
|
|
||
| export async function HomePage() { | ||
| const cookiesStore = await cookies(); | ||
| const session = await getServerComponentSession(cookiesStore); | ||
| console.log(session.userId); | ||
|
|
||
| /** | ||
| * SessionAuthForNextJS will handle proper redirection for the user based on the different session states. | ||
| * It will redirect to the login page if the session does not exist etc. | ||
| */ | ||
| 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.userId}</div> | ||
| <CallAPIButton /> | ||
| <ServerActionButton /> | ||
| </div> | ||
| </div> | ||
| <LinksComponent /> | ||
| <Image className={styles.separatorLine} src={SeparatorLine} alt="separator" /> | ||
| </div> | ||
| </SessionAuthForNextJS> | ||
| ); | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.