Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prerendering causing build error in SvelteKit #9809

Open
WhyAsh5114 opened this issue Jan 26, 2024 · 8 comments
Open

Prerendering causing build error in SvelteKit #9809

WhyAsh5114 opened this issue Jan 26, 2024 · 8 comments
Labels
bug Something isn't working svelte triage Unseen or unconfirmed by a maintainer yet. Provide extra information in the meantime.

Comments

@WhyAsh5114
Copy link

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.

@WhyAsh5114 WhyAsh5114 added bug Something isn't working triage Unseen or unconfirmed by a maintainer yet. Provide extra information in the meantime. labels Jan 26, 2024
@elron
Copy link

elron commented Jan 30, 2024

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
Copy link

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
Copy link
Member

ndom91 commented Feb 4, 2024

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.

  • You'll have to install that version of @auth/sveltekit
  • Add basePath: '/auth' to your hooks.server.ts or wherever you have your auth.js config. It is the default, but there still seems to be an issue there - I'll continue to investigate it, but adding the basepath manually to the config fixes it for now.
  • In addition, don't forget to add a secret value to your auth.js config (unrelated to this, but strongly suggested - I see that the repro you linked was missing it).

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
// /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 }),
  ],
});
// /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
Copy link
Author

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
Copy link
Member

ndom91 commented Feb 13, 2024

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
Copy link

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
Copy link
Author

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
Copy link
Member

ndom91 commented Mar 3, 2024

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

trunk-io bot pushed a commit to arcjet/arcjet-js that referenced this issue Jun 17, 2024
I can't find the actual part of the SvelteKit code that causes the import of `"$env/dynamic/private"` inside a node_module to fail, but I fixed our example so the problem surfaced.

I also discovered sveltejs/kit#12028 which states that a warning should be added that third-party libraries should not use this import. And nextauthjs/next-auth#9809 + nextauthjs/next-auth#10117 which highlight problems when it is used.

Perhaps we'll need to explore something like nextauthjs/next-auth#6247 but it seems that `process.env` is populated in SvelteKit so we can use it for now.

Fixes #982
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working svelte triage Unseen or unconfirmed by a maintainer yet. Provide extra information in the meantime.
Projects
None yet
Development

No branches or pull requests

6 participants