Cannot access url.searchParams Prerendering - SvelteKit

544 views Asked by At

I would like to make specific link from my page ( https://www.bizraport.pl/organizacje ) prerendered. My issue is that page uses (in both +page.server.js and +page.svelte) url.searchParams.get which makes an error:

Error: Cannot access url.searchParams on a page with prerendering enabled

I do get that there is infinite number of urls which can be created with parameters. However in my +page.server.js there is added export const prerender = 'auto'; and in svelte.config.js:

prerender: {
  entries: ["/organizacje"],
},

So why isn't it intelligent enough, to just get page /organizacje and do not worry about any url parameters. If there is any it should be standard approach (without prerender)

Links about similar topics:

https://dev.to/marcdaframe/sveltekit-dynamic-routes-static-renderer-17dl

How to use get parameter on sveltekit when use adapter-static?

Tried to make prerenderer work with specific url. This url is based on parameters, however not the main one. It may be filtered by additional parameters.

2

There are 2 answers

0
Valentin Vignal On

Here is a comment from Rich explaining why search parameters cannot be used during the pre-rendering:

When you prerender, you're writing files to the filesystem so that a simple webserver can serve them. Query parameters can't exist on the filesystem (both in the literal sense that ? isn't an allowed character on all filesystems, and in the sense that the webserver will ignore them), so if you have a prerendered endpoint called /api/posts/get then it doesn't matter how many times you call it with different parameters, it can only be saved as a file once. The files need to have different paths (/api/posts/[slug]), or it won't work.

A way around this is to use beforeUpdate:

<script>
  let myParameter = null;
  beforeUpdate(() => {
    myParameter =  url.searchParams.get('my-parameter');
  });
</script>

<div>
  <!-- Use `myParameter` -->
</div>
0
AudioBubble On

Accessing url.searchParams during prerendering is forbidden - on the server. As written in the documentation, you can get around this by retriving the parameters in the client, using onMount():

<script>
import { onMount } from 'svelte';

let page;

onMount(() => {
  params = url.searchParams.get('page');
})
</script>