This commit is contained in:
yohlo
2025-09-24 11:02:56 -05:00
parent 6760ea46f9
commit 36f3bb77d4
8 changed files with 34 additions and 14 deletions

View File

@@ -1,6 +1,7 @@
import {
createMiddleware,
createServerFn,
createServerOnlyFn,
} from "@tanstack/react-start";
import { getRequest, setResponseHeader } from "@tanstack/react-start/server";
import { redirect as redirect } from "@tanstack/react-router";
@@ -13,7 +14,23 @@ import { refreshSession } from "supertokens-node/recipe/session";
const logger = new Logger("Middleware");
export const verifySuperTokensSession = async (
function createNodeRequest(request: Request) {
const cookies = request.headers.get('cookie') || '';
return {
getHeaderValue: (key: string) => {
return request.headers.get(key) || undefined;
},
getCookieValue: (key: string) => {
const match = cookies.match(new RegExp(`(^| )${key}=([^;]+)`));
return match ? match[2] : undefined;
},
getMethod: () => request.method,
getOriginalURL: () => request.url,
};
}
const verifySuperTokensSession = async (
request: Request
) => {
let session = await getSessionForStart(request, { sessionRequired: false });
@@ -22,14 +39,18 @@ export const verifySuperTokensSession = async (
logger.info("Session needs refresh");
try {
const refreshedSession = await refreshSession(request, {
const nodeRequest = createNodeRequest(request);
const nodeResponse = {
setHeader: (key: string, value: string) => {
setResponseHeader(key, value);
},
setCookie: (cookie: string) => {
setResponseHeader('Set-Cookie', cookie);
}
});
};
const refreshedSession = await refreshSession(nodeRequest, nodeResponse);
if (refreshedSession) {
session = await getSessionForStart(request, { sessionRequired: false });
}
@@ -71,7 +92,7 @@ export const verifySuperTokensSession = async (
};
};
export const getSessionContext = async (request: Request, options?: { isServerFunction?: boolean }) => {
export const getSessionContext = createServerOnlyFn(async (request: Request, options?: { isServerFunction?: boolean }) => {
const session = await verifySuperTokensSession(request);
if (session.context.session?.tryRefresh) {
@@ -100,7 +121,7 @@ export const getSessionContext = async (request: Request, options?: { isServerFu
};
return context;
};
});
export const superTokensRequestMiddleware = createMiddleware({
type: "request",