Replies: 4 comments 4 replies
-
To give you a bit more context, since I will post this anyway... I've made an authentication library for this package, all based on Cloudflare products. Reasons for doing this will be posted as well. Since this is all rendered server side, I wish to keep it that way, and not create/user any AuthContext (since this is client side and uses JWT). No JWT is being used here. Now, since the sessions are controlled in the middleware, it would be nice it there would be a way of passing this session/user data through subsequent pages. This would mean that the page requested, if logged in, would get the session/user data and be able to use that information (like render a welcome message, I was hoping that we could leverage the worker context for this. If this is not possible, then please advise on a way to pass this data onto the requested pages. To be honest, repeating code in every page to retrieve the session/user data is not best practice (since we already do this in the middleware once). Hope you can help me, keen to post this already! |
Beta Was this translation helpful? Give feedback.
-
Hi @Mecanik 👋 Could you maybe put and retrieve things using That should work nicely as Something like creating and using a utility like this: export function getUserSession() {
const key = '__unique-auth-session-key__';
if (process.env[key]) {
return process.env[key];
}
const session = // generate user session data
process.env[key] = session;
return session;
} What do you think? would that work for you? |
Beta Was this translation helpful? Give feedback.
-
No, it would request the database only the first time you call it would also not matter who first calls Based on your example middleware, it could work something like this: Utility file: export function async getUserSession() {
const { env } = getRequestContext();
const key = '__unique-auth-session-key__';
if (process.env[key] !== undefined) {
return process.env[key];
}
// Attempt to retrieve the session cookie
const cookie = request.cookies.get(env.MK_SESSION_COOKIE_NAME);
if(!cookie) {
process.env[key] = null;
return;
}
const sessionData = await Database.getUserSession(env, cookie.value) ?? null;
process.env[key] = sessionData;
return sessionData;
} middleware: import { getUserSession } from 'utility-file';
export async function middleware(request: NextRequest) {
const url = new URL(request.url);
const pathname = url.pathname;
// Define public paths that should be accessible without authentication
const publicPaths = [
"/auth/register",
"/auth/register-confirm",
"/auth/login",
"/auth/password-reset",
"/api/auth",
];
// Check if the current path is one of the public paths
const isPublicPath = publicPaths.some((path) => pathname.startsWith(path));
try {
const sessionData = await getUserSession();
// If the user has a valid session (i.e., is logged in)
if (sessionData && !Utils.isTokenExpired(sessionData.expires_at)) {
// Redirect logged-in users away from public paths to the homepage
if (isPublicPath) {
return NextResponse.redirect(new URL("/", request.url));
}
// Allow logged-in users to continue to the rest of the app
return NextResponse.next();
}
// For not logged-in users: allow public paths, restrict others
if (!isPublicPath) {
// Redirect to login for any non-public paths if the user is not logged in
return NextResponse.redirect(new URL("/auth/login", request.url));
}
} catch (err) {
console.error("[_middleware][] Error:", err);
}
// Proceed with the request normally for public paths if no session exists
return NextResponse.next();
}
export const config = {
matcher: [
// Paths for dynamic pages and API excluding specified static assets and paths
"/((?!_next/static|_next/image|favicon.ico|next.svg|vercel.svg|images/|js/|css/|fonts/).*)",
],
}; page file: import { getUserSession } from 'utility-file';
export default function Page() {
// note: this simply retrieves the session data from `process.env`
const sessionData = await getUserSession();
// use sessionData
// ...
} what do you think? or am I misunderstanding something? |
Beta Was this translation helpful? Give feedback.
-
Based on your suggestions, this is what I did so far: session.ts:
middleware.ts:
page.ts:
Debug Log:
Please let me know your thoughts. It seems to persist. I have a few concerns, as this |
Beta Was this translation helpful? Give feedback.
-
Hi,
Is it possible to pass session data from middleware into the worker context?
Thanks
Beta Was this translation helpful? Give feedback.
All reactions