-
Notifications
You must be signed in to change notification settings - Fork 94
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
feat: Next.js SSR Improvements #877
Open
bcbogdan
wants to merge
24
commits into
master
Choose a base branch
from
feat/nextjs-ssr
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+3,734
−6
Open
Changes from all commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
57fbfc0
Add the base get session logic
bcbogdan a7594c1
Update the function and add types
bcbogdan e278f9f
Add more info about the proposal
bcbogdan d99eea4
Account for pages directory in the function implementation
bcbogdan 9796608
Update types and clean things up
bcbogdan f4d8d50
Add comments
bcbogdan 0109153
Add nextjs init function
bcbogdan 45467c2
Add the jose library
bcbogdan 88981c9
Fix refreshing and add example
bcbogdan 4613363
Fix build and token config
bcbogdan da4e86d
Fix payload processing
bcbogdan ad89bbe
Load config fron env variables
bcbogdan 08f9ca7
Add a redirect location during refresh
bcbogdan 4190020
Refresh token from middleware
bcbogdan 1d48378
Move everything in the library
bcbogdan 465f8d4
Rename files and update function singatures
bcbogdan 01e1533
Use the correct refresh path
bcbogdan ea95af2
Use normal responses instead of nextresponse
bcbogdan d366c32
Use normal request instead of nextrequest
bcbogdan 46f93b1
Cleanup implementation
bcbogdan 7c23d35
Revoke session inside the middleware
bcbogdan 531e5e9
Code review fixes
bcbogdan cfdc2af
Add tests for getSSRSession
bcbogdan f6651e7
Add tests for middleware
bcbogdan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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,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 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 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 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**. |
161 changes: 161 additions & 0 deletions
161
examples/with-next-ssr-app-directory/app/api/auth/[...path]/route.ts
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,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 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 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 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> | ||
); | ||
}; |
44 changes: 44 additions & 0 deletions
44
examples/with-next-ssr-app-directory/app/components/home.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,44 @@ | ||
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 { getSSRSession, init } from "supertokens-auth-react/nextjs/ssr"; | ||
import { ssrConfig } from "../config/ssr"; | ||
|
||
init(ssrConfig()); | ||
|
||
export async function HomePage() { | ||
const cookiesStore = await cookies(); | ||
const headersStore = await headers(); | ||
const session = await getSSRSession(cookiesStore, redirect); | ||
console.log(session); | ||
|
||
/** | ||
* 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 /> | ||
</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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'd say it handles redirections on the client side.