nextauthjs / next-auth

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

Prerendering causing build error in SvelteKit #9809

Open WhyAsh5114 opened 5 months ago

WhyAsh5114 commented 5 months ago

Environment

  System:
    OS: Windows 11 10.0.22621
    CPU: (12) x64 AMD Ryzen 5 3600 6-Core Processor
    Memory: 6.26 GB / 15.91 GB
  Binaries:
    Node: 18.18.2 - C:\Program Files\nodejs\node.EXE
    npm: 10.2.3 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Edge: Chromium (120.0.2210.144)
    Internet Explorer: 11.0.22621.1
  npmPackages:
    @auth/core: ^0.23.0 => 0.23.0
    @auth/sveltekit: ^0.9.0 => 0.9.0

Reproduction URL

https://github.com/WhyAsh5114/authjs-sveltekit-prerender

Describe the issue

Marking a route as prenderable with export const prerender = true creates a build error, usable in dev though. Removing the prerender line fixes it.

TypeError: Cannot read properties of undefined (reading 'length')
    at Object.handle (file:///D:/Programming/Web/authjs-sveltekit-prerender/.svelte-kit/output/server/chunks/hooks.server.js:49:24)
    at respond (file:///D:/Programming/Web/authjs-sveltekit-prerender/.svelte-kit/output/server/index.js:2650:43)
    at async visit (file:///D:/Programming/Web/authjs-sveltekit-prerender/node_modules/@sveltejs/kit/src/core/postbuild/prerender.js:202:20)

node:internal/event_target:1033
  process.nextTick(() => { throw err; });
                           ^
Error: 500 /prerender
To suppress or handle this error, implement `handleHttpError` in https://kit.svelte.dev/docs/configuration#prerender
    at file:///D:/Programming/Web/authjs-sveltekit-prerender/node_modules/@sveltejs/kit/src/core/config/options.js:202:13
    at file:///D:/Programming/Web/authjs-sveltekit-prerender/node_modules/@sveltejs/kit/src/core/postbuild/prerender.js:65:25
    at save (file:///D:/Programming/Web/authjs-sveltekit-prerender/node_modules/@sveltejs/kit/src/core/postbuild/prerender.js:403:4)
    at visit (file:///D:/Programming/Web/authjs-sveltekit-prerender/node_modules/@sveltejs/kit/src/core/postbuild/prerender.js:236:3)
Emitted 'error' event on Worker instance at:
    at [kOnErrorMessage] (node:internal/worker:300:10)
    at [kOnMessage] (node:internal/worker:311:37)
    at MessagePort.<anonymous> (node:internal/worker:212:57)
    at [nodejs.internal.kHybridDispatch] (node:internal/event_target:757:20)
    at exports.emitMessage (node:internal/per_context/messageport:23:28)

Node.js v18.18.2

How to reproduce

  1. Initialize new SvelteKit project, install @auth/sveltekit and @auth/core.
  2. Setup the handle hook with SvelteKitAuth()
  3. Create a prerenderable route, exclude it from validation in the root layout so it's accessible even if not logged in.
  4. Try building with npm run build.

Expected behavior

Build should succeed.

elron commented 5 months ago

I have the same issue with netlify build.

5:50:48 AM: ✓ built in 3.52s
5:50:49 AM: node:internal/event_target:1011
5:50:49 AM:   process.nextTick(() => { throw err; });
5:50:49 AM:                            ^
5:50:49 AM: ReferenceError [Error]: Request is not defined
5:50:49 AM:     at visit (file:///opt/build/repo/node_modules/@sveltejs/kit/src/core/postbuild/prerender.js:202:45)
5:50:49 AM:     at Object.fn (file:///opt/build/repo/node_modules/@sveltejs/kit/src/core/postbuild/prerender.js:184:22)
5:50:49 AM:     at dequeue (file:///opt/build/repo/node_modules/@sveltejs/kit/src/core/postbuild/queue.js:40:42)
5:50:49 AM:     at Object.add (file:///opt/build/repo/node_modules/@sveltejs/kit/src/core/postbuild/queue.js:67:4)
5:50:49 AM:     at enqueue (file:///opt/build/repo/node_modules/@sveltejs/kit/src/core/postbuild/prerender.js:184:12)
5:50:49 AM:     at prerender (file:///opt/build/repo/node_modules/@sveltejs/kit/src/core/postbuild/prerender.js:452:6)
5:50:49 AM:     at async MessagePort.<anonymous> (file:///opt/build/repo/node_modules/@sveltejs/kit/src/utils/fork.js:22:16)
5:50:49 AM: Emitted "error" event on Worker instance at:
5:50:49 AM:     at Worker.[kOnErrorMessage] (node:internal/worker:298:10)
5:50:49 AM:     at Worker.[kOnMessage] (node:internal/worker:309:37)
5:50:49 AM:     at MessagePort.<anonymous> (node:internal/worker:205:57)
5:50:49 AM:     at MessagePort.[nodejs.internal.kHybridDispatch] (node:internal/event_target:736:20)
5:50:49 AM:     at MessagePort.exports.emitMessage (node:internal/per_context/messageport:23:28)
5:50:49 AM: ​
5:50:49 AM: "build.command" failed                                        
5:50:49 AM: ────────────────────────────────────────────────────────────────
5:50:49 AM: ​
5:50:49 AM:   Error message
5:50:49 AM:   Command failed with exit code 1: npm run build (https://ntl.fyi/exit-code-1)
5:50:49 AM: ​
5:50:49 AM:   Error location
5:50:49 AM:   In Build command from Netlify app:
5:50:49 AM:   npm run build
5:50:49 AM: ​
5:50:49 AM:   Resolved config
5:50:49 AM:   build:
5:50:49 AM:     command: npm run build
5:50:49 AM:     commandOrigin: ui
5:50:49 AM:     environment:
5:50:49 AM:       - VITE_PUBLIC_WORDPRESS_API_URL
5:50:49 AM:     publish: /opt/build/repo/build
5:50:49 AM:     publishOrigin: ui
5:50:49 AM: Build failed due to a user error: Build script returned non-zero exit code: 2
5:50:49 AM: Failing build: Failed to build site
5:50:49 AM: Failed during stage "building site": Build script returned non-zero exit code: 2
5:50:49 AM: Finished processing build request in 23.884s

EDITED: Turns out I had Node version 16 in Netlify. I set Node version 20 and problem solved. Sharing this in case anyone encounters the same problem as I did...

Tom-Nudell commented 5 months ago

I'm getting the same error as @WhyAsh5114 when trying to build my project with sveltekit's static adapter. Error persists in Node.js v21.5.0, but I had the same error in Node.js v18.16.0.

Reproduce the bug by cloning sveltekit-auth-example and configure svelte.config.js the the static adapter default from https://kit.svelte.dev/docs/adapter-static

TypeError: Cannot read properties of undefined (reading 'length')
    at Object.handle (file:///sveltekit-auth-example/.svelte-kit/output/server/chunks/hooks.server.js:56:24)
    at respond (file:///sveltekit-auth-example/.svelte-kit/output/server/index.js:2713:43)
    at Server.respond (file:///Git/sveltekit-auth-example/.svelte-kit/output/server/index.js:2976:12)
    at generate_fallback (file:///Git/sveltekit-auth-example/node_modules/@sveltejs/kit/src/core/postbuild/fallback.js:38:32)
    at async MessagePort.<anonymous> (file://sveltekit-auth-example/node_modules/@sveltejs/kit/src/utils/fork.js:22:16)

node:internal/event_target:1096
  process.nextTick(() => { throw err; });
                           ^
Error: Could not create a fallback page — failed with status 500
    at generate_fallback (file:///sveltekit-auth-example/node_modules/@sveltejs/kit/src/core/postbuild/fallback.js:53:8)
    at async MessagePort.<anonymous> (file://sveltekit-auth-example/node_modules/@sveltejs/kit/src/utils/fork.js:22:16)

Node.js v21.5.0
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
ndom91 commented 4 months ago

Hey folks, sorry about this, we've just shipped a little fix in @auth/sveltekit@0.11.1 which takes the sveltekit exported base path into account.

Also on an unrelated note, you no longer need to explicitly install @auth/core. You can import the providers from @auth/sveltekit. For example:

import Google from "@auth/sveltekit/providers/google";
Working config ```ts // /src/auth.ts import { SvelteKitAuth } from "@auth/sveltekit"; import Google from "@auth/sveltekit/providers/google"; import { AUTH_GOOGLE_ID, AUTH_GOOGLE_SECRET } from "$env/static/private"; export const { handle } = SvelteKitAuth({ basePath: "/auth", secret: "abc", // Replace with output of `openssl rand -hex 32 | xc` from termianl providers: [ Google({ clientId: AUTH_GOOGLE_ID, clientSecret: AUTH_GOOGLE_SECRET }), ], }); ``` ```ts // /src/hooks.server.ts export { handle } from "./auth" ```

Making the above changes got your project (WhyAsh5114/authjs-sveltekit-prerender) to build successfully, including with the one route marked as prerender.

WhyAsh5114 commented 4 months ago

When using this new hooks.server.ts file with the latest @auth/sveltekit package:

import { SvelteKitAuth } from "@auth/sveltekit";
import Google from "@auth/sveltekit/providers/google";

export const { handle, signIn, signOut } = SvelteKitAuth({
  basePath: "/auth",
  providers: [Google],
  trustHost: true
});

I get this new error during build:

Error: Cannot read values from $env/dynamic/private while prerendering (attempted to read env.AUTH_URL). Use $env/static/private instead

What should I do to fix this?

ndom91 commented 4 months ago

When using this new hooks.server.ts file with the latest @auth/sveltekit package:

import { SvelteKitAuth } from "@auth/sveltekit";
import Google from "@auth/sveltekit/providers/google";

export const { handle, signIn, signOut } = SvelteKitAuth({
  basePath: "/auth",
  providers: [Google],
  trustHost: true
});

This is your hooks.server.ts? Using the latest @auth/sveltekit the config should be in a /src/auth.ts and the src/hooks.server.ts should just import and use the handle return value from SvelteKitAuth in /src/auth.ts.

Something like this:

image

Sorry for the confusion, new docs coming soon.

cdellinger commented 4 months ago

There still seems to be an issue here. If I create a latest sveltekit project and use @auth/sveltekit 0.13.0 I get the same error message when building as @WhyAsh5114 with the following code in auth.ts

export const { handle } = SvelteKitAuth({
    providers: [Google],
    callbacks: {
        async session({ session, user }) {
            session.user = {
                id: user.id, 
                name: user.name,
                email: user.email,
                image: user.image,
                emailVerified: user.emailVerified
            };
            return session;
        }
    },
    basePath: '/auth', 
    secret: AUTH_SECRET
});

and hooks.server.ts as follows: export { handle } from "./auth" As recommended at https://authjs.dev/reference/sveltekit#managing-the-session, I have a +layout.server.ts file as follows:

import type { LayoutServerLoad } from './$types';

export const load: LayoutServerLoad = async (event) => {
  return {
    session: await event.locals.getSession()
  };
};

If I comment out the line that sets the session, the error message disappears.

//session: await event.locals.getSession() Is the example at https://authjs.dev/reference/sveltekit#managing-the-session not to be followed any longer?

WhyAsh5114 commented 4 months ago

issue still persists, even after separating the auth.ts and hooks.server.ts, only occurs when prerendering Error: Cannot read values from $env/dynamic/private while prerendering (attempted to read env.AUTH_URL). Use $env/static/private instead

ndom91 commented 4 months ago

We're looking into it in #10117 if anyone wants to participate there atm