next-auth icon indicating copy to clipboard operation
next-auth copied to clipboard

in the middleware, the session is not extended with custom fields

Open SebastianNarvaez11 opened this issue 1 year ago • 42 comments

Environment

System: OS: Windows 11 10.0.22631 CPU: (12) x64 AMD Ryzen 5 3600 6-Core Processor Memory: 7.60 GB / 15.95 GB Binaries: Node: 20.11.0 - C:\Program Files\nodejs\node.EXE Yarn: 1.22.19 - C:\Program Files (x86)\Yarn\bin\yarn.CMD npm: 10.2.4 - C:\Program Files\nodejs\npm.CMD Browsers: Edge: Chromium (120.0.2210.91) Internet Explorer: 11.0.22621.1 npmPackages: @auth/prisma-adapter: ^1.1.0 => 1.1.0 next: 14.1.0 => 14.1.0 next-auth: 5.0.0-beta.5 => 5.0.0-beta.5 react: ^18 => 18.2.0

Reproduction URL

https://github.com/SebastianNarvaez11/TesloShop

Describe the issue

I am trying to get the custom field "role" in the middleware using req.auth but the custom fields that I added when creating the session previously are not there

In middleware.ts console.log(req.auth) : image

but with use auth() in the component it works : const session = await auth(); console.log(session) : image

How to reproduce

My file src/auth.ts : image

My file src/auth.config.ts: image

My file src/middleware.ts, the problem is here: image

Expected behavior

In the middleware you should have access to the custom fields that you added when creating the session

SebastianNarvaez11 avatar Jan 28 '24 16:01 SebastianNarvaez11

I too am facing this issue. The middleware's the only place I'm not having custom fields returned.

Have you been able to find a fix?

deltasierra96 avatar Feb 01 '24 22:02 deltasierra96

@deltasierra96 Nothing 😔

SebastianNarvaez11 avatar Feb 02 '24 13:02 SebastianNarvaez11

@SebastianNarvaez11 @deltasierra96

I also faced this issue, what seems to have worked for me was combining my NextAuth instantiations.

The Fix

You have called NextAuth(...) in src/middleware.ts and src/auth.ts using two different configurations. I was doing a similar thing. What you will want to do is move the content of the NextAuth(...) instantiation in src/auth.ts into src/auth.config.ts so that you have one main config with all your params for NextAuth(...).

Your src/auth.ts should now look a little something like:

import NextAuth from "next-auth";
import authConfig from "@/auth.config";

export const {
  handlers: { GET, POST },
  auth,
  signIn,
  signOut,
} = NextAuth(authConfig);

Your src/auth.config.ts should now have ALL your configuration in it:

import type { NextAuthConfig } from "next-auth";
// ... Prisma Imports

export default {
  providers: [...],
  pages: {
    signIn: "/auth/login",
    error: "/auth/error",
  },
  session: { strategy: "jwt" },

  callbacks: {
    authorized({ request, auth }) {
      console.log("Please Remove Me. This is a POC", auth) // <-- This should have your additional user data!
      return true;
    },
    async session({ token, session }) {
      if (token?.data?.role && session.user) {
        session.user.role = token.data.role;
      }

      return session;
    },
    async jwt({ token }) {
      // ... Your Prisma Code

      token.data = user    

      return token;
    },
  },
} satisfies NextAuthConfig;

This should resolve the issue. I have freehand typed this in GitHub so this code will probably not be perfect and will almost 100% have at least 1 error, but the idea should be there enough to hopefully help the issue.


The (assumed) Root Cause

It seems the actual cause is because the instantiations are different, calling NextAuth(...) in src/middleware.ts and src/auth.ts works perfectly fine after moving all the configuration settings into one file. Thinking logically now (after rage researching all day over not being able to find the solution to this) it makes perfect sense as in the example you provided (very similar to mine) the middleware would have no idea that the session needs manipulating as the session callback is not in the config being used in src/middleware.ts

TL;DR

You need to use one configuration/NextAuth instantiation for both your providers & middleware

  • Make one central auth config
  • Only call NextAuth once and export all the returned objects
  • Import "auth" from the previous step into the middleware
  • You should now see the role in your middleware auth user data.

Just follow the full fix, its not too long...


I hope that fixes your issue - If this is the problem for you, it seems the problem is NOT with next-auth. It may be worth documenting this somewhere though as its (IMO) an easy mistake to make!

ConnorC18 avatar Feb 04 '24 01:02 ConnorC18

@SebastianNarvaez11 @deltasierra96

I also faced this issue, what seems to have worked for me was combining my NextAuth instantiations.

The Fix

You have called NextAuth(...) in src/middleware.ts and src/auth.ts using two different configurations. I was doing a similar thing. What you will want to do is move the content of the NextAuth(...) instantiation in src/auth.ts into src/auth.config.ts so that you have one main config with all your params for NextAuth(...).

Your src/auth.ts should now look a little something like:

import NextAuth from "next-auth";
import authConfig from "@/auth.config";

export const {
  handlers: { GET, POST },
  auth,
  signIn,
  signOut,
} = NextAuth(authConfig);

Your src/auth.config.ts should now have ALL your configuration in it:

import type { NextAuthConfig } from "next-auth";
// ... Prisma Imports

export default {
  providers: [...],
  pages: {
    signIn: "/auth/login",
    error: "/auth/error",
  },
  session: { strategy: "jwt" },

  callbacks: {
    authorized({ request, auth }) {
      console.log("Please Remove Me. This is a POC", auth) // <-- This should have your additional user data!
      return true;
    },
    async session({ token, session }) {
      if (token?.data?.role && session.user) {
        session.user.role = token.data.role;
      }

      return session;
    },
    async jwt({ token }) {
      // ... Your Prisma Code

      token.data = user    

      return token;
    },
  },
} satisfies NextAuthConfig;

This should resolve the issue. I have freehand typed this in GitHub so this code will probably not be perfect and will almost 100% have at least 1 error, but the idea should be there enough to hopefully help the issue.

The (assumed) Root Cause

It seems the actual cause is because the instantiations are different, calling NextAuth(...) in src/middleware.ts and src/auth.ts works perfectly fine after moving all the configuration settings into one file. Thinking logically now (after rage researching all day over not being able to find the solution to this) it makes perfect sense as in the example you provided (very similar to mine) the middleware would have no idea that the session needs manipulating as the session callback is not in the config being used in src/middleware.ts

TL;DR

You need to use one configuration/NextAuth instantiation for both your providers & middleware

  • Make one central auth config
  • Only call NextAuth once and export all the returned objects
  • Import "auth" from the previous step into the middleware
  • You should now see the role in your middleware auth user data.

Just follow the full fix, its not too long...

I hope that fixes your issue - If this is the problem for you, it seems the problem is NOT with next-auth. It may be worth documenting this somewhere though as its (IMO) an easy mistake to make!

THIS ABSOLUTELY WORKS! Lets hope they either document it or fix it.

wizzyto12 avatar Feb 06 '24 13:02 wizzyto12

But with adapter: PrismaAdapter(prisma) when I move the callbacks: {...} from auth.ts to auth.config.ts I got the error [auth][cause]: Error: PrismaClient is unable to run in Vercel Edge Functions or Edge Middleware. As an alternative, try Accelerate: https://pris.ly/d/accelerate. Am I forced to use Accelerate to resolve this issue?

AmphibianDev avatar Feb 08 '24 08:02 AmphibianDev

Thanks for reporting, and thanks @ConnorC18 for explaining, that is exactly what we recommend at the moment. Some of us are working on a new doc to address this use-case, cc @ndom91 @ubbe-xyz 🙏

ThangHuuVu avatar Feb 08 '24 14:02 ThangHuuVu

@AmphibianDev I think you can define the adapter in the auth.ts file instead of the auth.config.ts file. See an example here in our dev app: https://github.com/nextauthjs/next-auth/blob/234a150e2cac3bc62a9162fa00ed7cb16a105244/apps/dev/nextjs/auth.ts#L37

ThangHuuVu avatar Feb 08 '24 14:02 ThangHuuVu

But with adapter: PrismaAdapter(prisma) when I move the callbacks: {...} from auth.ts to auth.config.ts I got the error [auth][cause]: Error: PrismaClient is unable to run in Vercel Edge Functions or Edge Middleware. As an alternative, try Accelerate: https://pris.ly/d/accelerate. Am I forced to use Accelerate to resolve this issue?

Prisma doesn't support edge runtimes yet though, that's right.

In their most recent change log for 5.9.0 they mentioned bringing out support for it (outside of accelerate). So hopefully it'll here soon 🤞

Thanks for the ping though thang. Definitely something we have to be clear about in the docs 👍

ndom91 avatar Feb 08 '24 15:02 ndom91

@ThangHuuVu

@AmphibianDev, I think you can define the adapter in the auth.ts file instead of the auth.config.ts file. See an example here in our dev app:

I already did; here is my repo: https://github.com/AmphibianDev/todo-app. The only thing that I am missing is the user role-based routing in the middleware.ts, and the project is done. But I can't do that because req.auth?.user?.role is always undefined.

@ndom91, are you saying it's impossible for me to get the user custom fields user.role in the middleware without using the edge runtime? I want to deploy my Next.js app on a VPS together with PostgreSQL, so I want to stay away from the edge.

I'm quite new to Next.js and next-auth, so I started with a simple ToDo App to get the hang of things. Sorry to bother, but I have one more question, if I may: If I protect a route in the auth((req) => {...}); middleware, for example, if (req.nextUrl.pathname.includes("/protected")) return Response.redirect(new URL("/", req.nextUrl));, do I still need to protect the server actions that are run in the "/protected" page.tsx?

AmphibianDev avatar Feb 08 '24 18:02 AmphibianDev

@AmphibianDev ah okay, no so only if you're running on an edge runtime then Prisma has issues, although they can be worked around like implied by Thang and ConnorC18 detailed. "slef hosting" the Next.js app on a VPS should be fine. Make sure to use @prisma/[email protected], they just released a little fix that makes this better.

Regarding your second question the mdidleware runs in front of every request (unless you white / blacklist something in the "matchers" setting), so your server actions should be covered :+1:

ndom91 avatar Feb 08 '24 18:02 ndom91

only if you're running on an edge runtime then Prisma has issues, although they can be worked around like implied by Thang and ConnorC18 detailed.

@ndom91, I did like ConnorC18 and Thang implied, but I got the error:

[auth][error] JWTSessionError: Read more at https://errors.authjs.dev#jwtsessionerror
[auth][cause]: Error: PrismaClient is unable to run in Vercel Edge Functions or Edge Middleware. As an alternative, try Accelerate: https://pris.ly/d/accelerate.
If this is unexpected, please open an issue: https://pris.ly/prisma-prisma-bug-report
    at Object.get (C:\Users\Work\Desktop\todo-app\.next\server\edge\chunks\node_modules_4328cd._.js:4744:23)
    at Object.jwt (C:\Users\Work\Desktop\todo-app\.next\server\edge\chunks\_f42337._.js:147:153)
    at Module.session (C:\Users\Work\Desktop\todo-app\.next\server\edge\chunks\node_modules_d0ec2d._.js:3091:43)
    at async Module.AuthInternal (C:\Users\Work\Desktop\todo-app\.next\server\edge\chunks\node_modules_d0ec2d._.js:3582:24)
    at async Module.Auth (C:\Users\Work\Desktop\todo-app\.next\server\edge\chunks\node_modules_d0ec2d._.js:3722:29)
    at async handleAuth (C:\Users\Work\Desktop\todo-app\.next\server\edge\chunks\node_modules_4328cd._.js:3120:29)
    at async Module.adapter (C:\Users\Work\Desktop\todo-app\.next\server\edge\chunks\_540240._.js:6699:16)
    at async runWithTaggedErrors (C:\Users\Work\Desktop\todo-app\node_modules\next\dist\server\web\sandbox\sandbox.js:99:24)
    at async DevServer.runMiddleware (C:\Users\Work\Desktop\todo-app\node_modules\next\dist\server\next-server.js:1039:24)
    at async DevServer.runMiddleware (C:\Users\Work\Desktop\todo-app\node_modules\next\dist\server\dev\next-dev-server.js:261:28)
[auth][details]: {}

If I move the callbacks: {...} or the adapter: PrismaAdapter(prisma) from auth.js into the auth.config.js I go to the error. And as I understand, I need to move the callbacks: {...} into the auth.config.js to have the user custom fields in the middleware auth((req) => {...});. Did I got it wrong?

AmphibianDev avatar Feb 08 '24 18:02 AmphibianDev

@AmphibianDev make sure you are not calling prisma in the middleware.ts handler. I don't believe this error is caused by the PrismaAdapter; the PrismaClient causes it. Just make sure you are not using prisma in the middleware

ConnorC18 avatar Feb 08 '24 20:02 ConnorC18

@AmphibianDev

If I move the callbacks: {...} or the adapter: PrismaAdapter(prisma) from auth.js into the auth.config.js

Also make sure you are copying over session: { strategy: "jwt" }, into the auth.config.js as not having this in the config while adapter: PrismaAdapter(prisma) is present might also cause this issue.

ConnorC18 avatar Feb 08 '24 20:02 ConnorC18

@ConnorC18 Believe me, I have tried every combination of moves possible. :sweat: The only working one, but with no user custom filed in the middleware is: {pages, callbacks, adapter, session, jwt, ...authConfig} in auth.ts and {providers} in auth.config.ts I have tried:

  1. auth.ts {...authConfig}, auth.config.ts {pages, callbacks, adapter, session, jwt, providers}
  2. auth.ts {pages, adapter, ...authConfig}, auth.config.ts {callbacks, session, jwt, providers}
  3. ... 4. ... 5. ... :sob:

I have removed any auth check from my app and made it easier to spin up: https://github.com/AmphibianDev/todo-app You just need to remove the .example from .env.example and: npm install, docker compose up -d, npx prisma db push and for the login can be anything like [email protected] and 1234 for the 2FA.

I want to make this work so bad... :disappointed:

AmphibianDev avatar Feb 08 '24 21:02 AmphibianDev

Hi everyone. Here's a thumb rule you can follow:

  1. Define all config in a single place - auth.config.ts
  2. In auth.ts export the following:
export const { handlers, auth, signIn, signOut } = NextAuth({...authConfig})
  1. Use the exported handlers in /api/auth/[...nextAuth]/app.ts.

All is good until you want to add middleware.ts.

Now you should be able to use the same exported auth from auth.ts but since there are adapters that are not compatible with middleware, you cannot use them YET. I am trying to use postgres with drizzle-orm and at the time of writing this, only neon serverless has a postgres connector.

How did I resolve this?

I moved the adapter and any callbacks requiring DB access into auth.ts. I had to reinitialize NextAuth in middleware as follows:

import NextAuth from 'next-auth'

import { authConfig } from './auth.config'

const auth = NextAuth(authConfig).auth

export default auth((req) => {
// Do some routing stuff here if you want
// The `req.auth` will have all the fields that you returned via the `session` callback
})

Use the above hack until the adapters support running on edge. BTW - I spent 2 days setting up the Next Auth v5. I finally completed it. Here are my thoughts:

  1. The current documentation state is not good. Refer to this video for any setup-related issues: https://www.youtube.com/watch?v=1MTyCvS05V4&t=15629s. Shoutout to whoever created this.
  2. After setup, things are much simpler and easier to handle.
  3. I even created my adapter because of my requirements using drizzle.
  4. AdapterModels should be implemented in a way that we can override stuff. I needed my userId to be an integer, which is not possible at all without raising a bunch of errors in NextAuth. Used the cal.com GitHub repo to understand how to do this.

jainmohit2001 avatar Feb 09 '24 12:02 jainmohit2001

Hi everyone. Here's a thumb rule you can follow:

  1. Define all config in a single place - auth.config.ts
  2. In auth.ts export the following:
export const { handlers, auth, signIn, signOut } = NextAuth({...authConfig})
  1. Use the exported handlers in /api/auth/[...nextAuth]/app.ts.

All is good until you want to add middleware.ts.

Now you should be able to use the same exported auth from auth.ts but since there are adapters that are not compatible with middleware, you cannot use them YET.

How did I resolve this?

I moved the adapter and any callbacks requiring DB access into auth.ts. I had to reinitialize NextAuth in middleware as follows:

import NextAuth from 'next-auth'

import { authConfig } from './auth.config'

const auth = NextAuth(authConfig).auth

export default auth((req) => {
// Do some routing stuff here if you want
// The `req.auth` will have all the fields that you returned via the `session` callback
})

Use the above hack until the adapters support running on edge. BTW - I spent 2 days setting up the Next Auth v5. I finally completed it. Here are my thoughts:

  1. The current documentation state is not good. Refer to this video for any setup-related issues: https://www.youtube.com/watch?v=1MTyCvS05V4&t=15629s. Shoutout to whoever created this.
  2. After setup, things are much simpler and easier to handle.
  3. I even created my adapter because of my requirements using drizzle.
  4. AdapterModels should be implemented in a way that we can override stuff. I needed my userId to be an integer, which is not possible at all without raising a bunch of errors in NextAuth. Used the cal.com GitHub repo to understand how to do this.

Im currently battleing this behaviour too, fighting it for 6 days now. Can you please share your code so we can see what was done in order to get this going? I have tried using prisma - only with accelerate which is paid, drizzle - "edgeFunction is not defined".

wizzyto12 avatar Feb 09 '24 13:02 wizzyto12

// The req.auth will have all the fields that you returned via the session callback

@jainmohit2001 I don't get it, I tried following what you said, but they still don't have all the fields returned from the session callback, in the middleware.

middleware.ts

import NextAuth from "next-auth";
import authConfig from "@/auth.config";

const { auth } = NextAuth(authConfig);

export default auth((req) => {
  console.log(req.auth?.user); // => only { email: '[email protected]' }
});

export const config = {
  matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/", "/(api|trpc)(.*)"],
};

auth.ts

import NextAuth from "next-auth";
import authConfig from "@/auth.config";
import prisma from "@/lib/prisma";
import { PrismaAdapter } from "@auth/prisma-adapter";

export const {
  handlers: { GET, POST },
  auth,
  signIn,
  signOut,
} = NextAuth({
  callbacks: {
    async session({ session, token }) {
      if (token.sub && session.user) {
        session.user.id = token.sub;
        session.user.role = token.role;
      }

      return session;
    },
    async jwt({ token }) {
      if (!token.sub) return token;

      const user = await prisma.user.findUnique({
        where: { id: token.sub },
      });

      if (!user) return token;

      token.role = user.role;

      return token;
    },
  },
  adapter: PrismaAdapter(prisma),
  ...authConfig,
});

auth.config.ts

import { NextAuthConfig } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { $LogInSchema } from "./lib/validation";
import prisma from "@/lib/prisma";
import { User as PrismaUser, UserRole } from "@prisma/client";

import { JWT } from "next-auth/jwt";
declare module "next-auth/jwt" {
  interface JWT {
    role: UserRole;
  }
}

declare module "next-auth" {
  interface User extends PrismaUser {}
}

export default {
  session: { strategy: "jwt" },
  pages: {
    signIn: "/auth/login",
    error: "/auth/error",
  },
  providers: [
    CredentialsProvider({
      credentials: {
        email: { label: "Email", type: "email" },
        phone: { label: "Phone", type: "tel" },
      },
      async authorize(credentials, req) {
        const validatedFields = $LogInSchema.safeParse(credentials);

        if (validatedFields.success) {
          const { email, phone } = validatedFields.data;
          const user = await prisma.user.findFirst({
            where: {
              OR: [{ email }, { phone }],
            },
          });

          if (!user) return null;

          return user;
        }

        return null;
      },
    }),
  ],
} satisfies NextAuthConfig;

AmphibianDev avatar Feb 09 '24 14:02 AmphibianDev

Guys sorry to bother but how about my case? I am doing a subdomain in my middleware.

export default NextAuth(authConfig).auth(middleware);

async function middleware(req: NextRequest) {

  const url = req.nextUrl;
  const hostname = getHostname(req.headers.get("host")!);
  const path = getPath(url.pathname, url.searchParams.toString());

  const isBusSearch = isBusSearchPath(path);
  if (isBusSearch) {
    const [, origin, destination] = isBusSearch;
    return NextResponse.redirect(`${MONOLITH_LINK}/onibus/${origin}/${destination}`);
  }

  if (shouldRewriteRootApplication(hostname)) {
    const rewrittenUrl = getRewrittenUrl("/home", path, new URL(req.url));
    return NextResponse.rewrite(rewrittenUrl);
  }

  const subdomain = getSubdomain(hostname);
  if (subdomain !== "www") {
    const rewrittenUrl = getRewrittenUrl(`/${subdomain}`, path, new URL(req.url));
    return NextResponse.rewrite(rewrittenUrl);
  }
}

function getRewrittenUrl(basePath: string, path: string, reqUrl: URL): URL {
  return new URL(`${basePath}${path === "/" ? "" : path}`, reqUrl);
}

The problem is the auth seems to run before the middleware.

JorgeMadson avatar Feb 09 '24 14:02 JorgeMadson

Hi @AmphibianDev. A good starting point would be to turn on the logger for the NextAuth by providing a logger param and see the debug output.

It seems like you are using CredentialsProvider. I am afraid I won't be able to tell the issue for this. I am using EmailProvider.

I can point out that the jwt and session callbacks are required in auth.config.ts as well. Please try adding those callbacks and console.log whatever you are getting and see if the required data is present or not.

jainmohit2001 avatar Feb 09 '24 16:02 jainmohit2001

@jainmohit2001 You gave me hope again, I was literally just writing about giving up, and your message popped up, I even started to have PTSD when I opened the auth's files :sob: I added the session and jwt to both the auth.ts and auth.config.ts, no difference. And how do I turn on the logger? I only found this:

import log from "logging-service" //-> Cannot find module 'logging-service' or its corresponding type declarations.ts(2307)

export default NextAuth({
  logger: {
    error(code, ...message) {
      log.error(code, message)
    },
    warn(code, ...message) {
      log.warn(code, message)
    },
    debug(code, ...message) {
      log.debug(code, message)
    }
  }
})

And I added the below code into the auth.ts, but I got nothing in the console.

NextAuth({
  debug: true,
  logger: {
    error(code, ...message) {
      console.log(`${code}  ${message}`);
    },
    warn(code, ...message) {
      console.log(`${code}  ${message}`);
    },
    debug(code, ...message) {
      console.log(`${code}  ${message}`);
    },
  },
...

AmphibianDev avatar Feb 09 '24 17:02 AmphibianDev

@AmphibianDev I think this is almost 100% a workaround, but it seems to work and is why my one currently works. If you are running it in a non-edge environment, I think this approach is fine.

To check this actually works, I've made the changes and made a PR for this. Others can check the code here for an easier to read breakdown of the required changes but the explanation below might be useful

Fix PR ...For AmphibianDev

https://github.com/AmphibianDev/todo-app/pull/1

auth.config.ts

  import prisma from "@/lib/prisma";
  import { NextAuthConfig } from "next-auth";
  import CredentialsProvider from "next-auth/providers/credentials";

  import { $LogInSchema } from "./lib/validation";
+ import { getUserById } from "./data/user";
+ import { PrismaAdapter } from "@auth/prisma-adapter";

  export default {
    providers: [
      // Your provider stuff from before... Nothing has changed here
    ],
+   // We have moved the callbacks into this file
    callbacks: {
      async session({ session, token }) {
        if (token.sub && session.user) {
          session.user.id = token.sub;
        }

        if (session.user) {
          session.user.id = token.sub;
          session.user.role = token.role;
        }

        return session;
      },
      async jwt({ token }) {
        if (!token.sub) return token;

-       const user = await prisma.user.findUnique({
-         where: { id: token.sub },
-       });

+       const user = await getUserById(token.sub);

        if (!user) return token;

        token.role = user.role;

        return token;
      },
    },
+   // We have moved the session into this file
    session: { strategy: "jwt", maxAge: 365 * 24 * 60 * 60 },
+   // We have moved the jwt into this file
    jwt: { maxAge: 365 * 24 * 60 * 60 },
+   // We have moved the adapter into this file
    adapter: PrismaAdapter(prisma),
  } satisfies NextAuthConfig;

auth.ts

import NextAuth from "next-auth";
import authConfig from "@/auth.config";

export const {
  handlers: { GET, POST },
  auth,
  signIn,
  signOut,
} = NextAuth({
  pages: {
    signIn: "/auth/login",
    error: "/auth/error",
  },
  ...authConfig,
});

middleware.ts

//... Other Imports
import NextAuth from "next-auth";
import authConfig from "@/auth.config";
const { auth } = NextAuth(authConfig);

export default auth((req) => {
  const { nextUrl } = req;
  const pathname = nextUrl.pathname;

  const isLoggedIn = !!req.auth;

  const isAdmin = req.auth?.user?.role === "ADMIN";
  console.log(req.auth?.user); // => { email: '[email protected]' }
//... The rest of your code here
})

/data/user.ts

import prisma from "@/lib/prisma";

export const getUserById = async (id: string) => {
  try {
    const user = await prisma.user.findUnique({ where: { id } });

    return user;
  } catch {
    return null;
  }
};

So whats the workaround?

Basically it looks like the workaround is to import a function that calls prisma independently and then just await that function. Doing this seems to solve the issue. If this is a valid work around this 100% needs documenting, and if it is, it really needs to be made clearer.

ConnorC18 avatar Feb 09 '24 17:02 ConnorC18

Hi @ConnorC18. Thanks for helping out @AmphibianDev with the PR. Appreciate it!!

A quick question: Is Prisma actually running on middleware using this approach? I have my doubts since Prisma is not edge-compatible. Are you able to build the project using npm run build ?

jainmohit2001 avatar Feb 09 '24 17:02 jainmohit2001

Hi @ConnorC18. Thanks for helping out @AmphibianDev with the PR. Appreciate it!!

A quick question: Is Prisma actually running on middleware using this approach? I have my doubts since Prisma is not edge-compatible. Are you able to build the project using npm run build ?

No worries! So, I am exclusively looking at this from a Non Edge standpoint, as that is what myself and @AmphibianDev are both using in this case. As far as I can see, it builds fine and runs (with the exception of the session callback having a es-line type issue in @AmphibianDev s case, but I believe that is because he needs to update his next-auth version, as I do not have this issue with the same approach). After building, the following successful output can be seen for @AmphibianDev s project

image

ConnorC18 avatar Feb 09 '24 17:02 ConnorC18

Well seems like Prisma can work in edge runtime. I am using postgres package with drizzle-orm so no luck. Here's an issue that might be of use if you ever come across this in future https://github.com/vercel/next.js/issues/28774#issuecomment-1526897155

Edit: I am also using a DB adapter! Needed in EmailProvider.

jainmohit2001 avatar Feb 09 '24 17:02 jainmohit2001

image

Here's an image thats keeping me sane about the whole authentication system. I really miss those Django days.

jainmohit2001 avatar Feb 09 '24 18:02 jainmohit2001

Big thanks to ConnorC18 for the amazing help! :star::star::star::star::star:

es-line type issue in @AmphibianDev s case, but I believe that is because he needs to update his next-auth version

./auth.config.ts:42:30
Type error: Property 'token' does not exist on type '({ session: Session; user: AdapterUser; } | { session: Session; token: JWT; }) & { newSession: any; trigger?: "update" | undefined; }'.

  40 |   ],
  41 |   callbacks: {
> 42 |     async session({ session, token }) {

Right again, this happens on "next-auth": "^5.0.0-beta.5". After installing the "next-auth": "^5.0.0-beta.9", it disappeared. I am now fully happy! Right before, I was about to give up. :sweat_smile:

AmphibianDev avatar Feb 09 '24 18:02 AmphibianDev

Also quick note, Prisma is beginning to release edge compatible clients. In their latest 5.9.1 release they already updated it to not throw when imported in an edge runtime, but only at query-time. So you can at least import it in files imported in middleware, as long as your not making any queries. Should simplify the auth.ts split workaround as well.

Just remember to use @prisma/[email protected]+ and session: { strategy: "jwt" } :+1:

ndom91 avatar Feb 10 '24 00:02 ndom91

i'm facing the same issue. So far the only solution i found is to use Prisma on the edge following this article: https://www.prisma.io/blog/database-access-on-the-edge-8F0t1s1BqOJE.

idhard avatar Feb 11 '24 12:02 idhard

Yeah so historically the only option has been Prisma Accelarate. This is just a db connection pooler behind an HTTP endpoint, so you all you needed was an http client (fetch, axios, etc.) and that's something you find in any runtime (edge, node, etc.).

But now they're seemingly slowly but surely shipping "real" edge runtime support.

Upgrading the @primsa/[email protected], using jwt session strategy, and not doing any DB queries in your middleware, for example, will already work today.

ndom91 avatar Feb 13 '24 20:02 ndom91

@ndom91 do you know if Prisma edge client is compatible with Supabase Supavisor https://github.com/supabase/supavisor/blob/main/README.md.

idhard avatar Feb 13 '24 20:02 idhard