Skip to content
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
wants to merge 24 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions examples/with-next-ssr-app-directory/.env
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
3 changes: 3 additions & 0 deletions examples/with-next-ssr-app-directory/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}
38 changes: 38 additions & 0 deletions examples/with-next-ssr-app-directory/.gitignore
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
42 changes: 42 additions & 0 deletions examples/with-next-ssr-app-directory/README.md
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 examples/with-next-ssr-app-directory/app/api/auth/[...path]/route.ts
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 examples/with-next-ssr-app-directory/app/api/user/route.ts
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 examples/with-next-ssr-app-directory/app/auth/[[...path]]/page.tsx
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;
}
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 examples/with-next-ssr-app-directory/app/components/home.tsx
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.
Comment on lines +22 to +23
Copy link
Collaborator

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.

*/
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>
);
}
Loading
Loading