Authentication and getting authenticated user in multiple components
Unanswered
Labrador Duck posted this in #help-forum
Labrador DuckOP
Hey there I am implementing authentication in my app. It is a database auth with storing session info in cookies.
The issue I am facing is I want to store authenticated user details in something like global context so that I can access it in multiple components like in homepage and in layout for protecting routes and also for providing value to navbar for customizing for auth user.
Currently I have a function name getCurrentUser so it is called two times.
In Astro I would do like set userInfo like userId in Astro.locals.userId in the middleware and it can be accessed anywhere without any db call.
Is there anything somewhat similar that I can do in Next.js?
The issue I am facing is I want to store authenticated user details in something like global context so that I can access it in multiple components like in homepage and in layout for protecting routes and also for providing value to navbar for customizing for auth user.
Currently I have a function name getCurrentUser so it is called two times.
In Astro I would do like set userInfo like userId in Astro.locals.userId in the middleware and it can be accessed anywhere without any db call.
Is there anything somewhat similar that I can do in Next.js?
6 Replies
Marble gall
do you use any libs ?
Labrador DuckOP
No I am not using any lib
@Labrador Duck No I am not using any lib
Marble gall
https://nextjs.org/docs/app/building-your-application/authentication
i think you ought to use one of the libs for authentication, it makes storing authenticated user details so ez.
i think you ought to use one of the libs for authentication, it makes storing authenticated user details so ez.
Labrador DuckOP
I don't think that is solving the issue. I have tried NextAuth
Labrador DuckOP
Currently I am doing something like this
export async function middleware(request: NextRequest) {
const sessionId = cookies().get("auth_token");
const requestHeaders = new Headers(request.headers);
if (sessionId) {
const userInfo = await getCurrentUser(sessionId)
if (userInfo && userInfo.user) {
requestHeaders.set("app_user", userInfo.user?.id);
}
}
return NextResponse.next({ request: { headers: requestHeaders } });
}
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};Is there any security consideration I should take care or anything else?