Encountering an issue with the SSR module evaluation despite having SSR disabled in Svelte Kit

I needed a specific route in my app to not be server-side rendered. This can be achieved by setting export const ssr = false in the module script or configuring ssr: false in the svelte.config.js, as outlined in the Svelte documentation.

Despite disabling SSR using both methods, I encountered errors in the terminal such as localStorage is not defined, which should not occur with SSR disabled.

The app continues to function properly. However, whenever I reload the page in the browser, this error reappears in the terminal.

[vite] Error when evaluating SSR module /src/routes/index.svelte:
ReferenceError: localStorage is not defined

svelte.config.js

import preprocess from 'svelte-preprocess';
import adapter from '@sveltejs/adapter-static';

/** @type {import('@sveltejs/kit').Config} */
const config = {
    // Consult https://github.com/sveltejs/svelte-preprocess
    // for more information about preprocessors
    preprocess: preprocess(),
    kit: {
        ssr: false,
        adapter: adapter({
            fallback: '200.html'
        }),
        prerender: {
            enabled: false
        },
    }
};

export default config;

index.svelte

<script context="module" lang="ts">
    export const ssr = false
</script>

<script lang="ts">
    import Yrtc from "./../helpers/Yrtc";
    import { onMount } from "svelte";

    onMount(() => {
        const yrtc = new Yrtc({
            roomId: 'tet-riieiiasds-di'
        })

        console.log({yrtc})
    })
</script>
test

Answer №1

Currently, with SvelteKit version 1.20.4, the code functions as intended. It's important to note that some elements in the original code example have been removed or are unnecessary for solving the issue:

const config = {
    // ...
    kit: {
        ssr: false,
        prerender: {
            enabled: false
        },
        // ...
    }
};

The presence of these two options individually will result in errors like "Unexpected option config.kit.ssr" and "Unexpected option config.kit.prerender.enabled," causing the build process to halt.

<script context="module">
    export const ssr = false
</script>

Regardless of whether it's within the module script tags, a warning message is triggered: "export const ssr will be ignored — move it to +page(.server).js/ts instead. See for more information."

The reason behind this requirement is that accessing the exported ssr property from a +page.svelte file necessitates loading the component and its imports, which can lead to issues at a later stage.

If the export is relocated to either of these files (+page(.server).js/ts), it should function correctly. Here's how you can replicate the scenario:

  • Create a new project using the demo app template:
    npm create svelte@latest no-ssr-test && cd no-ssr-test && npm i
  • In src/routes/+page.svelte, add console.log(window)
  • Run the application with npm run dev to observe the error
    ReferenceError: window is not defined
  • In src/routes/+page.js (or similar), add export const ssr = false
  • Running again with npm run dev should restore the site functionality

Answer №2

Elements like localStorage, document, and self are not available on the server-side. To utilize these elements, use them within the onMount function which executes only in the browser after the component has been rendered:

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

  onMount(() => {
    document.createElement(...);
    
    // ...
  });
</script>

Source:

If you're using an external module that relies on these elements, utilize the import() function to dynamically load the module at runtime:

<script>
    import { onMount } from 'svelte'

    onMount(async () => {
        const Plotly = await import('plotly.js-dist-min')

        // ...
    })
</script>

Source:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountered an error: Unable to access property '0' of an undefined variable

Below is the script I am using: <script> var count; var obj; function search() { xhr = new XMLHttpRequest(); xhr.open("GET", "test.json", true); xhr.send(null); xhr.onreadystatechange = function() { if (xhr.readyState == 4 & ...

Utilize the dynamic duo of GridLayout and ScrollView within the Famo.us JS framework

I'm attempting to incorporate a grid layout into a scroll view using famo.us (with angular), and the most straightforward approach seems to be working. <fa-view> <fa-scroll-view fa-pipe-from="eventHandler" fa-options="scrollView"> ...

Java Selenium Javascript executor fails to return desired result

Attempting to execute a javascript function I created to gather all comments from an HTML site using xpath (requirement). The function, when pasted directly into a browser without the 'return' statement, works flawlessly. However, when run th ...

Navigating through a collection of objects

My array consists of objects, each having the following structure: var car = { make: "", model: "", price: "" } I am attempting to iterate through each object and check if a specific property is defined in this manner: for (i = 0; i <= ...

The JSON property is not defined

After making an AJAX call to retrieve data, I receive a JSON Object instead of a string. When I log the object, all its properties appear correctly. However, when attempting to log one specific property, it shows up as undefined. Here is a snapshot of my ...

Saving dynamic text input values to the database using asynchronous communication with AJAX

PHP: foreach ($_POST['fields'] as $fieldIndex => $fieldValue) { $stmt = $dbconnect->prepare('INSERT INTO '); <<=== How to insert values $stmt->execute(); } JQuery: $("#add").click(functio ...

Line of cubes - tap on a single cube and the others gracefully slide away from view

I am working on a project where I need to create a row of blocks. The goal is for the blocks to slide off the screen when one is clicked, leaving the clicked block in the first position. For instance: https://i.sstatic.net/IB5LI.jpg I attempted using jQ ...

Using Handlebars JS to incorporate HTML tags such as <li>, <br>, and more in your data

Is there a way to use handlebars to display a list of data in an unordered format, with "title" and "articles" as the main categories? The issue arises when some of the articles contain HTML tags, such as <a> for links. In my current code, instead of ...

The default value of the select option will not be displayed upon loading and will also not appear when another option is selected

I created a form using vue.js that includes a select option dropdown. However, the default value does not display when the form loads, and when a new option is selected from the dropdown, it also does not show. When I use v-for to loop through all options ...

Observables in Knockout.js vanish after being bound

I'm encountering a peculiar issue with my Knockout script. Here is the viewModel: viewModel = { viewShown: function () { if (params.id !== undefined) timer = setInterval(loadVorgangsdetails, 100); else { $( ...

JSON string inside a string-type in AWS model

My goal is to create a basic model that can accept a JSON string instead of defining all variables/elements upfront. The model will have an "options" element which will hold a JSON string. Below is the structure of my model. { "$schema": "http://json-sch ...

Synchronous CORS XHR encounters issues with 302 redirect, while asynchronous function successfully redirects

Why does Firefox seem to be the only browser that doesn't throw an error when performing a synchronous request? Any insights on this peculiar behavior? // Ensure your JS console is open when running this script var url = '//api.soundcloud.com/ ...

Guide to displaying a local HTML file in CKEditor 4.3 using jQuery

Using CKEditor 4.3 on my HTML page, I aim to import content from a local HTML file and display it within the editor. (My apologies for any English errors as I am Brazilian :P) The jQuery code I have tried is as follows: $(document).ready(function(){ ...

On initial load, React router switch fails to find a match

I am encountering an issue with my switch and react-router. Whenever I open a new tab and navigate to any path, it always redirects me to /login. However, if I remove the bottom switch (the one without a path - the default), everything works as expected. A ...

Can you please explain the significance of the code "!!~this.roles.indexOf('*')" within the MEAN.io framework?

One particular line of code can be found in the startup file for the MEAN framework. if (!!~this.roles.indexOf('*')) { This specific line is located within the shouldRender function of the menus.client.service.js file, which resides in the publ ...

Discovering the channel editor on Discord using the channelUpdate event

While working on the creation of the event updateChannel, I noticed that in the Discord.JS Docs, there isn't clear information on how to identify who edited a channel. Is it even possible? Below is the current code snippet that I have: Using Discord. ...

Ways to retrieve every span within a string variable that possesses a specific class designation

I'm having trouble listing out all spans with the class "ansspans." There may be one or more span elements with the "ansspans" class, and I need to retrieve them along with their content in order to iterate through them. Can someone explain how to do ...

What is the most efficient way to query through a Firestore database containing 5,000 users?

We are currently facing a challenge with our staffing application, which is built using vuejs and a firestore database containing over 5,000 users. Our primary issue lies in the need for a more efficient layout that allows admins to search for users within ...

What is the best way to transfer data from a component to a .ts file that contains an array?

I am currently developing a budgeting application and I have a component that is responsible for holding values that I want to pass to an array stored in a separate file. While I can retrieve data from the array, I am facing difficulty in figuring out how ...

Transforming an SQL Query into JSON format using Oracle 11g in Oracle Application Express (APEX)

In my Oracle APEX v4.2 project, I am dealing with a sizable table containing about 40 columns and up to 50 rows. My goal is to use SQL to fetch the data from this table and convert each row into a JSON object. Operating on Oracle 11gR2, I require this JSO ...