Session not received as authenticated during a GET request
See original GitHub issueProvider 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:
- Created a year ago
- Reactions:5
- Comments:15 (2 by maintainers)
@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:
`let res = await fetch(“http://localhost:3000/api/posts”, { method: “GET”, headers: {
});`
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