question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

getSession and getToken are undefined when calling api routes from getServerSideProps

See original GitHub issue

Description 🐜

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 ☕️

  1. create a default page component that exports a getServerSideProps() fn.
  2. create a short api route that simply checks for a session using getSession()
  3. trigger a fetch request to that api endpoint from getServerSideProps()
  4. 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:closed
  • Created 2 years ago
  • Reactions:1
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

2reactions
servcommented, Oct 9, 2021

NOTE: you shouldn’t fetch from API routes inside gSSP.

https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering

Thanks for this info.

Next.js doc reaffirms this.

Write server-side code directly Note that getStaticProps runs only on the server-side. It will never be run on the client-side. It won’t even be included in the JS bundle for the browser. That means you can write code such as direct database queries without them being sent to browsers. You should not fetch an API route from getStaticProps — instead, you can write the server-side code directly in getStaticProps.

1reaction
balazsorban44commented, Aug 13, 2021
Read more comments on GitHub >

github_iconTop Results From Across the Web

Using getToken in getServerSideProps() · Issue #720 - GitHub
Digging into the code, it's because req.cookies is undefined in my req object. I got it working by parsing the cookie manually using ......
Read more >
Next Auth getSession not working in api routes - Stack Overflow
I get a valid object. But when I call it in the API that is called in that getServerSideProps() function, I get null....
Read more >
Securing pages and API routes - NextAuth.js
The methods getSession() and getToken() both return an object if a session is valid and null if a session is invalid or has...
Read more >
Data Fetching: getServerSideProps - Next.js
An API route is used to fetch some data from a CMS. That API route is then called directly from getServerSideProps . This...
Read more >
getserversideprops nextauth - You.com | The AI Search ...
When i try to make a request via apollo client in getServerSideProps, then getSession is suddenly null in the api route. api route...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found