getSession and getToken are undefined when calling api routes from getServerSideProps
See original GitHub issueDescription 🐜
Hey guys I’m not sure if this is a feature or a bug, but it’s def something that is hindering me from being able to verify authentication on the server.
NOTE: client-side calls to the same route do succeed in verifying the token/session.
I’ll try to explain the issue as best as I can…
I have a next.js api route: “/api/user/me”
I’m attempting to call this route from getServerSideProps()
,
ALSO NOTE: I’m using SWR for data-fetching
export async function getServerSideProps(ctx) {
const { jsonFetcher } = await import("@/utils");
const data = await jsonFetcher(`http://localhost:3000/api/user/me`);
if (!data)
return {
notFound: true,
};
return {
props: {
initialData: data,
},
};
} else {
const errorMessage = "You don't have permission to access this page";
return {
redirect: {
destination: `/user/${ctx.query.id}/posts/?${errorMessage}`,
permanenet: false,
},
props: {},
};
}
}
On the server i’m handling the request as such:
import { getSession } from "next-auth/client";
export default async (req, res) => {
const session = await getSession({ req });
if (session) {
const user = await getMe();
res.json(user);
} else {
return res.status(401).send("Unauthorized");
}
};
The api route should then check for and validate my session using getSession, but this returns null on the server when called from getServerSideProps
.
The endpoint works perfectly fine when being called from the client-side of the app, but for some reason the behavior seems to act differently in both environments.
Would be
Is this a bug in your own project?
No
How to reproduce ☕️
- create a default page component that exports a
getServerSideProps()
fn. - create a short api route that simply checks for a session using
getSession()
- trigger a fetch request to that api endpoint from
getServerSideProps()
- session will be === null.
Screenshots / Logs 📽
No response
Environment 🖥
npx: installed 1 in 2.373s
System: OS: macOS High Sierra 10.13.6 CPU: (4) x64 Intel® Core™ i5 CPU 760 @ 2.80GHz Memory: 72.85 MB / 16.00 GB Shell: 5.3 - /bin/zsh Binaries: Node: 14.15.0 - ~/.nvm/versions/node/v14.15.0/bin/node Yarn: 1.22.4 - ~/.yarn/bin/yarn npm: 6.14.5 - ~/.nvm/versions/node/v14.15.0/bin/npm Browsers: Edge: 92.0.902.62 Firefox: 89.0.2 npmPackages: next: ^11.0.0 => 11.0.1 next-auth: latest => 3.27.3 react: ^17.0.2 => 17.0.2
Contributing 🙌🏽
No, I am afraid I cannot help regarding this
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:5 (1 by maintainers)
Thanks for this info.
Next.js doc reaffirms this.
NOTE: you shouldn’t fetch from API routes inside gSSP.
https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering