-
Notifications
You must be signed in to change notification settings - Fork 94
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
improv: add an improved way of refreshing the session during SSR
Update the function and add types Add more info about the proposal Account for pages directory in the function implementation Update types and clean things up Add comments Add nextjs init function Add the jose library Fix refreshing and add example Fix build and token config Fix payload processing Load config fron env variables Add a redirect location during refresh Refresh token from middleware Move everything in the library Rename files and update function singatures Use the correct refresh path Use normal responses instead of nextresponse Use normal request instead of nextrequest Cleanup implementation Revoke session inside the middleware Code review fixes Add tests for getSSRSession Add tests for middleware
- Loading branch information
Showing
390 changed files
with
27,925 additions
and
47,883 deletions.
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> | ||
); | ||
}; |
43 changes: 43 additions & 0 deletions
43
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,43 @@ | ||
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 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.