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.

Session not received as authenticated during a GET request

See original GitHub issue

Provider type

Credentials

Environment

System: OS: Windows 10 10.0.19044 CPU: (4) x64 Intel® Core™ i5-7300HQ CPU @ 2.50GHz Memory: 5.06 GB / 15.87 GB Binaries: Node: 14.17.5 - C:\Program Files\nodejs\node.EXE Yarn: 1.22.17 - ~\AppData\Roaming\npm\yarn.CMD npm: 8.1.3 - C:\Program Files\nodejs\npm.CMD Browsers: Edge: Spartan (44.19041.1266.0), Chromium (99.0.1150.46) Internet Explorer: 11.0.19041.1566 npmPackages: next: ^12.0.10 => 12.0.10 next-auth: ^4.2.1 => 4.2.1 react: 17.0.2 => 17.0.2

Reproduction URL

https://github.com/ParidV/Dua-n-pu

Describe the issue

getSession returning null in Get requests, in POST request the session is okay.

Component

`export async function getServerSideProps(context) {
  const res = await axios.get(`${process.env.API_URL}/company/jobs`);
  return {
    props: {
      jobs: res.data.jobs,
    },
  };
}`

API Request api/company/jobs/index.js

import { getSession } from "next-auth/react";

export default async (req, res) => {
  const { method } = req;
  switch (method) {
    case "GET":
      try {
        const session = await getSession({ req });

        console.log(session + " SESSION "); //RETURN NULL

        console.log(JSON.stringify(session));
        const jobs = await prisma.jobs.findMany({
          where:{
            userId: session.id
          }
        });
        return res.status(200).json({ success: true, jobs });
      } catch (error) {
        return res.status(404).json({
          success: false,
          message: error.message,
        });
      }

How to reproduce

In POST request, the session is okay, but when I make a get request to get the ID from the server to pass in the axios request come as NULL.

Expected behavior

It should return the session

Issue Analytics

  • State:open
  • Created a year ago
  • Reactions:5
  • Comments:15 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
luismbcrcommented, Sep 20, 2022

@markmendozadev maybe this is a late response, but I faced the same issue with POST method, I could access the session, but not with POST, after doing some research, I found this is because NextJS does not send the cookies in the header for GET method, so I fixed the issue like this:

image

`let res = await fetch(“http://localhost:3000/api/posts”, { method: “GET”, headers: {

  "Content-Type": "application/json",
  // I have to add cookie in the GET 
  Cookie: context.req.headers.cookie,
},

});`

1reaction
markmendozadevcommented, Apr 4, 2022

Hi @ParidV Yes i think i found my answers already but not 100% sure. It works on client-side because getSession works on client-side requests.

if you do a request on your api through client side (not using any next data fetching just pure react it will 100% work) i mean the authentication.

now i did a little digging and here’s what i found (https://github.com/nextauthjs/next-auth/pull/4116)

@jaminecode my _app.js already like that

import "../styles/globals.css";
import { SessionProvider } from "next-auth/react";
import Layout from "../components/layout/Layout";

function MyApp({ Component, pageProps: { session, ...pageProps } }) {
  return (
    <SessionProvider session={session}>
      <Layout>
        <Component {...pageProps} />
      </Layout>
    </SessionProvider>
  );
}
export default MyApp;

Read more comments on GitHub >

github_iconTop Results From Across the Web

session for authenticated user is not being set - Stack Overflow
Whenever a user logs in with the right credentials the server returns "success" as response, but always directs me back to the base...
Read more >
Authenticating and Obtaining a Session ID
The session ID can be retrieved either as part of the JSON response, or else as a cookie. If authentication is not done,...
Read more >
Understanding Authentication - REST API - DevNet
When the session is created, a session ID that looks like a GUID is generated and assigned to it by the server. It...
Read more >
401 Unauthorized - HTTP - MDN Web Docs
This status code is sent with an HTTP WWW-Authenticate response header that contains information on how the client can request for the resource ......
Read more >
Redirect Users - Auth0
Using cookies and browser sessions. Using state parameters. During a user's authentication, the redirect_uri request parameter is used as a callback URL.
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