api.getSession in pages router

Hi! How should I fetch the session server-side (getServerSideProps or API route) when using Next.js' pages router? Both of these seem to work but they give TypeScript errors:
const session = await auth.api.getSession(req);
// Argument of type 'NextApiRequest' is not assignable to parameter of type '{ headers: Headers; query?: { disableCookieCache?: boolean | undefined; disableRefresh?: boolean | undefined; } | undefined; asResponse?: boolean | undefined; }'.
const session = await auth.api.getSession(req);
// Argument of type 'NextApiRequest' is not assignable to parameter of type '{ headers: Headers; query?: { disableCookieCache?: boolean | undefined; disableRefresh?: boolean | undefined; } | undefined; asResponse?: boolean | undefined; }'.
const session = await auth.api.getSession({
headers: req.headers,
});
// Type 'IncomingHttpHeaders' is missing the following properties from type 'Headers': append, delete, get, getSetCookie, and 7 more.
const session = await auth.api.getSession({
headers: req.headers,
});
// Type 'IncomingHttpHeaders' is missing the following properties from type 'Headers': append, delete, get, getSetCookie, and 7 more.
Thank you!
2 Replies
The Untraceable
The Untraceable2mo ago
Not 100% sure if there is any other way to do this. I can't find any underlying raw request attached to the NextApiRequest to find the native Headers object, so you can just manually make it.
const headers = new Headers();
Object.entries(req.headers).forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach(v => nativeHeaders.append(key, v));
} else if (value !== undefined) {
nativeHeaders.set(key, value);
}
});
const headers = new Headers();
Object.entries(req.headers).forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach(v => nativeHeaders.append(key, v));
} else if (value !== undefined) {
nativeHeaders.set(key, value);
}
});
Maybe extract that into a toHeaders util. Or you could use app router for just api requests and have access to NextRequest and NextResponse which has a headers attribute the perfect type (or pass in the entire request). I'd imagine you wouldn't want to though
whyburg
whyburgOP2mo ago
Good enough for me, thank you so much!

Did you find this page helpful?