How can I get the request object from a layout function?
Answered
Dutch Smoushond posted this in #help-forum
Dutch SmoushondOP
I am using Auth0 which is initialized on the server side with the getSession function. However this function takes a request as an input. I'm not sure what information it's actually using inside getSession function, I'm assuming some cookie information. Is there a way to get access to the entire request object from the layout?
Answered by Dutch Smoushond
After reviewing further, it looks like auth0 is using the request object as a caching mechanism. You can actually call getSession with no parameters and auth0 will pull the necessary data from cookies in next/headers.
2 Replies
Dutch SmoushondOP
I was able to workaround this by creating a new request object. But it would be great to have a function to get actual request object. Here is the code if anyone is interested. It's from this ticket: https://github.com/auth0/nextjs-auth0/issues/1193
import { headers } from 'next/headers'
import { getSession as auth0GetSession } from '@auth0/nextjs-auth0'
import { IncomingMessage, ServerResponse } from 'http'
import { Socket } from 'net'
const reqRes = () => {
const req = new IncomingMessage(new Socket())
headers().forEach((v, k) => {
req.headers[k] = v
})
const res = new ServerResponse(req)
return { req, res }
}
export const getSession = () => {
const { req, res } = reqRes()
return auth0GetSession(req, res)
}
import { headers } from 'next/headers'
import { getSession as auth0GetSession } from '@auth0/nextjs-auth0'
import { IncomingMessage, ServerResponse } from 'http'
import { Socket } from 'net'
const reqRes = () => {
const req = new IncomingMessage(new Socket())
headers().forEach((v, k) => {
req.headers[k] = v
})
const res = new ServerResponse(req)
return { req, res }
}
export const getSession = () => {
const { req, res } = reqRes()
return auth0GetSession(req, res)
}
Dutch SmoushondOP
After reviewing further, it looks like auth0 is using the request object as a caching mechanism. You can actually call getSession with no parameters and auth0 will pull the necessary data from cookies in next/headers.
Answer