Skip to content

prerender when using hooks.server.js #9965

Closed
@coryvirok

Description

@coryvirok

Describe the bug

I'm not sure if this is a bug or not but I was confused by it so maybe we need a docs update.

The issue is that even though +layout.js exports export const prerender = false the build step will invoke hooks.server.js with the URL. If there is logic in the hooks.server.js#handle() function that is not prerenderable, (e.g. accessing event.url.search) the build will fail.

I assumed that since the layout disabled prerendering for its page tree, handle() would not even be invoked.

I think it's pretty common to have non-prerenderable code in hooks.server.js. In my case, I check auth and then redirect to /login?next=PATH_AND_SEARCH_OF_ORIGINAL_URL which breaks prerender.

The workaround is to check building in hooks.server.js before doing anything non-prerenderable. This probably deserves a mention in the docs since handle() will be invoked even for non-prerenderable URLs.

Reproduction

https://stackblitz.com/edit/sveltejs-kit-template-default-dapyhy?file=src/hooks.server.js

Run npm run build

Logs

No response

System Info

System:
    OS: Linux 5.0 undefined
    CPU: (2) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 0 Bytes / 0 Bytes
    Shell: 1.0 - /bin/jsh
  Binaries:
    Node: 16.14.2 - /usr/local/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 7.17.0 - /usr/local/bin/npm
  npmPackages:
    @sveltejs/adapter-node: latest => 1.2.4 
    @sveltejs/kit: ^1.5.0 => 1.17.0 
    svelte: ^3.54.0 => 3.59.1 
    vite: ^4.3.0 => 4.3.7

Severity

serious, but I can work around it

Additional Information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions