Next-auth: GetSession on API route (what am I missing?)

Created on 2 Sep 2020  路  3Comments  路  Source: nextauthjs/next-auth

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.

  • [x] Found the documentation helpful
  • [ ] Found documentation but was incomplete
  • [ ] Could not find relevant documentation
  • [x] Found the example project helpful
  • [ ] Did not find the example project helpful
question

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.

  const b = await fetch(`${process.env.HOST}/api/item`, {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      cookie: context.req.headers.cookie,
    },
  });

All 3 comments

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,
    },
  });
Was this page helpful?
0 / 5 - 0 ratings

Related issues

bscaspar picture bscaspar  路  3Comments

ryanbahan picture ryanbahan  路  3Comments

alex-cory picture alex-cory  路  3Comments

iaincollins picture iaincollins  路  3Comments

eatrocks picture eatrocks  路  3Comments