Your question
I've been following the demo and documentation and trying to fetch sessions on an API route (eg. /pages/api/feed.js) so I can associate userid with any posts, as well as verify that a user is logged in.
However, despite being logged in on the client side and being able to fetch everything successfully, no session data seems to make it over to the api. I feel like I must be missing something obvious, but
One thing to point out is that I'm using DB sessions and not JWT
import { PrismaClient } from "@prisma/client";
import { getSession } from "next-auth/client";
const prisma = new PrismaClient();
export default async function handle(req, res) {
const session = await getSession({ req });
console.log("Session", session);
if (session) {
const posts = await prisma.post.findMany({
where: {},
include: { media: true },
});
console.log(posts);
res.json(posts);
} else {
res.send([]);
}
}
What are you trying to do
Protect API endpoints and return appropriate data on call
Feedback
Documentation refers to searching through online documentation, code comments and issue history. The example project refers to next-auth-example.
Hi @readywater
In your [...next-auth].js, you can check/debug callbacks to verify what values are being returned, or modify them.
Try:
https://next-auth.js.org/configuration/callbacks#session-callback
@SharadKumar Thanks for the reply! I'm using the debugger, and sessions do return properly when queried from the client side, including when using getserverside props, but when I query the above endpoint directly, there's zero debug information from next-auth.
This is how I'm fetching the above endpoint, as an aside:
export const getServerSideProps = async () => {
const res = await fetch(`${process.env.HOST}/api/feed`);
let feed;
try {
feed = await res.json();
} catch (e) {
console.log("error:", e.message);
}
return {
props: { feed, url: process.env.HOST },
};
};
Just a brief continuation of this mystery.
When using Fetch with a POST the getSession() function is able to retrieve the session, but return null on a GET. So I'm wondering if I'm failing to pass something when using GET.
Argh. I'm dumb.
For anyone who finds this, here's the proper options. I was just looking in the wrong place in the example.
const b = await fetch(`${process.env.HOST}/api/item`, {
method: "GET",
headers: {
"Content-Type": "application/json",
cookie: context.req.headers.cookie,
},
});
Most helpful comment
Just a brief continuation of this mystery.
When using Fetch with a POST the getSession() function is able to retrieve the session, but return null on a GET. So I'm wondering if I'm failing to pass something when using GET.
Argh. I'm dumb.
For anyone who finds this, here's the proper options. I was just looking in the wrong place in the example.