#Accessing Session in nextjs middleware for next-auth

2 messages · Page 1 of 1 (latest)

silver abyss
#

Hello, I need to access the session to extract which user is using the api in the nextauth middleware, this is vital to the use of my app and I do not want to have to invoke a function manually on every route as there is a lot of them, Here is my middleware code so far,

/middleware.ts

import { PrismaClient } from "@prisma/client";
import { getServerSession } from "next-auth";
import { getSession } from "next-auth/react";
import { NextResponse } from "next/server";
import { NextRequest } from "next/server";
import { authOptions } from "./app/api/auth/[...nextauth]/route";

const prisma = new PrismaClient();

export async function middleware(req: NextRequest) {
  const sessionAttempt1 = await getSession({ req }); // returns null
  const sessionAttempt2 = await getServerSession(authOptions); // throws error

  return NextResponse.next();
}

export const config = {
  matcher: "/api/users/:path*",
};

here are the error messages:

sessionAttempt1:
https://paste.rs/mJwsj.txt

and the sessionAttempt1 object logs "null"

sessionAttempt2:

 ⨯ node_modules/oidc-token-hash/lib/shake256.js (3:0) @ <unknown>
 ⨯ Cannot read properties of undefined (reading 'substring')
null

I cannot think of how to extract this session, That is the last part of my app, Any help is thoroughly appreciated.

as well as this, Using either of these session retrieval functions in an api route works absolutely fine, How annoying

stable coyoteBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)