Replies: 7 comments 4 replies
-
If you use an edge runtime, you can validate the session via middleware with something like this.
BUT, if you use a "node runtime", then you will get an exception while running The error message is:
So, you can check "is there a cookie" but not "is the session valid". |
Beta Was this translation helpful? Give feedback.
-
Workaround is to call an internal api endpoint which checks the session. Here the example: // middleware
const pathname = request.nextUrl.pathname
const origin = request.nextUrl.origin
if (AUTH_EXCLUDE.includes(pathname)) {
return next()
}
// this is just an workaround to handle the auth verification
// inside the middleware - Since the middleware is "edge only"
// we have to call an internal api endpoint to run the lucia magic ;)
const verifyRequest = await fetch(`${origin}/api/auth/verify-session`, {
// without this, we can't check the cookie in the called api route
headers: { Cookie: cookies().toString() },
})
const verifySession = (await verifyRequest.json()) as {
valid: boolean
}
if (!verifySession.valid) {
// invalid session
return NextResponse.redirect(new URL("/auth", request.nextUrl))
}
// everything seems ok
return next() // src/app/api/auth/verify-session/route.ts
import type { NextRequest } from "next/server"
import { NextResponse } from "next/server"
// here you have to update the import - I'm using a mono repo and the auth stuff is located in a package
import { lucia } from "@acme/auth"
const handler = async (req: NextRequest) => {
const sessionId = req.cookies.get(lucia.sessionCookieName)?.value ?? null
// no cookie exists
if (!sessionId) {
return NextResponse.json({ valid: false })
}
const { session } = await lucia.validateSession(sessionId)
if (!session) {
return NextResponse.json({ valid: false })
}
return NextResponse.json({ valid: true })
}
export { handler as GET } |
Beta Was this translation helpful? Give feedback.
-
If you need an example, I have updated my template repo: https://github.com/noxify/t3-turbo-lucia/tree/main |
Beta Was this translation helpful? Give feedback.
-
You'd still need to access the user data in |
Beta Was this translation helpful? Give feedback.
-
I totally agree with @pilcrowonpaper, you should not overcomplicate it. RSC gave us the opportunity to safely fetch and check at the same place and I would say 99.99% of protected pages need the user data already anyway. If you don't want to write 4 lines of code everytime, create another function that does the check and redirects if necessary. Now you got a one-liner again for every page. export const validateProtected = async () => {
const req = await validateRequest();
if (!req.session) {
redirect("/login");
}
return req;
}; |
Beta Was this translation helpful? Give feedback.
-
I'm going to chime in here and say it would be great to have a built-in way of checking auth state in the middleware. A use case I'm running into is rendering a Without the workaround of validating through another internal API endpoint I don't think I have a way of getting that information. Either way, seems to me that having the option is better in general (I've been using it in SvelteKit for a while now). If somebody explained how to go about this I'd be happy to make a PR. |
Beta Was this translation helpful? Give feedback.
-
So the same applies for other libraries using the middleware for authentication? For instance when using next auth, if we check the session in the middleware and then we check and get it again in a server component we do 2 round trips? (one for middleware and one for the server component?) |
Beta Was this translation helpful? Give feedback.
-
It's possible to use Lucia Auth in the middleware.ts to check for authorization in protected routes like in Auth.js?
const { user } = await validateRequest();
if(!user) redirect("/");
It's not practical to check user on every page
Beta Was this translation helpful? Give feedback.
All reactions