nextauthjs / next-auth

Authentication for the Web.
https://authjs.dev
ISC License
24.96k stars 3.52k forks source link

Middleware marked with `server-only` in Next 13 fails to build #8560

Closed barryengineerapart closed 1 year ago

barryengineerapart commented 1 year ago

Environment

Operating System:
      Platform: darwin
      Arch: arm64
      Version: Darwin Kernel Version 22.6.0: Wed Jul  5 22:21:53 PDT 2023; root:xnu-8796.141.3~6/RELEASE_ARM64_T6020
    Binaries:
      Node: 18.16.0
      npm: 9.5.1
      Yarn: N/A
      pnpm: N/A
    Relevant Packages:
      next: 13.4.12
      eslint-config-next: 13.4.12
      react: 18.2.0
      react-dom: 18.2.0
      typescript: 5.1.6
    Next.js Config:
      output: N/A

Reproduction URL

https://codesandbox.io/p/sandbox/vigorous-ace-sx277k?file=/middleware.ts:1,1

Describe the issue

Nextjs13 will fail to build when using server-only with middleware (even if the middleware is empty like so):

import "server-only";
export function middleware() {}

This is problematic for AuthJS which uses middleware which is exposed to sensitive information that must not be in any circumstances be shared with the client. This could be a problem with NextJS (see https://github.com/vercel/next.js/issues/55206) which may be incorrectly including some middleware components in the client build.

How to reproduce

  1. Create an empty NextJS 13 instance.
  2. Include the following middleware:
    import "server-only";
    export function middleware() {}

Expected behavior

Since the current guidance of AuthJS is to use middleware that potentially exposes client secrets, the thinking is that the middleware should never be exposed to a client build. This could be a Next problem, however next may also be using middleware on the client (I can't be sure).

However, the expected behavior is that AuthJS can be used in a safe/secure manner, and so there should be some way to ensure the middleware can use server functions without exposing sensitive info to the client. Perhaps this could mean using fetch (which may increase the latency somewhat).

adrianyg7 commented 1 year ago

Currently having this issue where nothing from the auth files marked as server-only, which contain sensitive data, can be imported into middlewares, specially the ongoing v5 that directly requires importing the auth config file into the middleware file.

balazsorban44 commented 1 year ago

This is unrelated to NextAuth.js. already tracked on the Next.js side. https://github.com/vercel/next.js/issues/54549

balazsorban44 commented 1 year ago

@adrianyg7 FWIW I've tested this locally a few times, and have deployment where this works. Make sure you are on the latest Next.js/NextAuth.js version. 🤔

barryengineerapart commented 1 year ago

@adrianyg7 FWIW I've tested this locally a few times, and have deployment where this works. Make sure you are on the latest Next.js/NextAuth.js version. 🤔

Does that mean that this issue has been solved>