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: add nextjs session utils #767

Merged
merged 16 commits into from
Jan 4, 2024
2 changes: 1 addition & 1 deletion .github/workflows/pre-commit-hook-run.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,5 @@ jobs:
with:
node-version: "16"
- run: git init && git add --all && git -c user.name='test' -c user.email='[email protected]' commit -m 'init for pr action'
- run: npm i --force
- run: npm i --force && cd test/with-typescript && npm i --force
- run: ./hooks/pre-commit.sh
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [unreleased]
rishabhpoddar marked this conversation as resolved.
Show resolved Hide resolved

## [16.7.0] - 2023-12-22

- Add session util functions `withSession`, `getSSRSession` and `withPreParsedRequestResponse` for Next.js App directory.
rishabhpoddar marked this conversation as resolved.
Show resolved Hide resolved
- Previously, the custom framework's `errorHandler` callback function was invoked only upon encountering an error. This behavior has been rectified, and now the callback is invoked in both error and success cases.

## [16.6.8] - 2023-12-18

- Fix App dir support by removing the import of the "http" module
Expand Down
4 changes: 3 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ You will need to setup the `supertokens-core` in order to to run the `supertoken
3. `cd supertokens-node`
4. Install the project dependencies
`npm i -d`
5. Add git pre-commit hooks
5. Install the dependencies inside `test/with-typescript`
`cd test/with-typescript && npm i && cd ../..`
6. Add git pre-commit hooks
`npm run set-up-hooks`

## Modifying Code
Expand Down
9 changes: 7 additions & 2 deletions examples/next/with-emailpassword/app/api/user/route.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import { NextResponse, NextRequest } from "next/server";
import { withSession } from "../../../middleware";
rishabhpoddar marked this conversation as resolved.
Show resolved Hide resolved
import { withSession } from "supertokens-node/nextjs";
import supertokens from "supertokens-node";
import { backendConfig } from "../../../config/backendConfig";

supertokens.init(backendConfig());

export async function GET(request: NextRequest) {
return withSession(request, async (session) => {
return withSession(request, async (err, session) => {
if (err) return NextResponse.json(err, { status: 500 });
if (session === undefined) {
return new NextResponse("Authentication required", {
status: 401,
Expand Down
44 changes: 4 additions & 40 deletions examples/next/with-emailpassword/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import Session, { SessionContainer } from "supertokens-node/recipe/session";
import { SessionContainer } from "supertokens-node/recipe/session";
import supertokens from "supertokens-node";
import { backendConfig } from "./config/backendConfig";
import { withSession } from "supertokens-node/nextjs";

supertokens.init(backendConfig());

Expand All @@ -12,7 +13,8 @@ export async function middleware(request: NextRequest & { session?: SessionConta
return NextResponse.next();
}

return withSession(request, async (session) => {
return withSession(request, async (err, session) => {
if (err) return NextResponse.json(err, { status: 500 });
if (session === undefined) {
return NextResponse.next();
}
Expand All @@ -27,41 +29,3 @@ export async function middleware(request: NextRequest & { session?: SessionConta
export const config = {
matcher: "/api/:path*",
};

export async function withSession(
request: NextRequest,
handler: (session: SessionContainer | undefined) => Promise<NextResponse>
) {
try {
const token = request.cookies.get("sAccessToken");
if (token === undefined) {
return handler(undefined);
}
const accessToken = token.value;
let session = await Session.getSessionWithoutRequestResponse(accessToken, undefined, {
sessionRequired: false,
});
let response = await handler(session);
if (session !== undefined) {
let tokens = session.getAllSessionTokensDangerously();
if (tokens.accessAndFrontTokenUpdated) {
response.cookies.set({
name: "sAccessToken",
value: tokens.accessToken,
httpOnly: true,
path: "/",
expires: Date.now() + 3153600000000,
});
response.headers.append("front-token", tokens.frontToken);
}
}
return response;
} catch (err) {
if (Session.Error.isErrorFromSuperTokens(err)) {
return new Response("Authentication required", {
status: err.type === Session.Error.INVALID_CLAIMS ? 403 : 401,
});
}
throw err;
}
}
42 changes: 21 additions & 21 deletions examples/next/with-emailpassword/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions lib/build/framework/custom/framework.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ const errorHandler = () => {
const userContext = utils_1.makeDefaultUserContextFromAPI(request);
try {
await supertokens.errorHandler(err, request, response, userContext);
return next();
} catch (err) {
return next(err);
}
Expand Down
7 changes: 2 additions & 5 deletions lib/build/framework/utils.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import type { Request, Response } from "express";
import type { IncomingMessage } from "http";
import { ServerResponse } from "http";
import type { HTTPMethod } from "../types";
import { NextApiRequest } from "next";
export declare function getCookieValueFromHeaders(headers: any, key: string): string | undefined;
export declare function getCookieValueFromIncomingMessage(request: IncomingMessage, key: string): string | undefined;
export declare function getHeaderValueFromIncomingMessage(request: IncomingMessage, key: string): string | undefined;
Expand All @@ -13,11 +12,9 @@ export declare function parseJSONBodyFromRequest(req: IncomingMessage): Promise<
export declare function parseURLEncodedFormData(req: IncomingMessage): Promise<any>;
export declare function assertThatBodyParserHasBeenUsedForExpressLikeRequest(
method: HTTPMethod,
request: Request | NextApiRequest
): Promise<void>;
export declare function assertFormDataBodyParserHasBeenUsedForExpressLikeRequest(
request: Request | NextApiRequest
request: Request
): Promise<void>;
export declare function assertFormDataBodyParserHasBeenUsedForExpressLikeRequest(request: Request): Promise<void>;
export declare function setHeaderForExpressLikeResponse(
res: Response,
key: string,
Expand Down
29 changes: 29 additions & 0 deletions lib/build/nextjs.d.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading