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

Include a parent class within the style tags in your CSS code

Currently, I am facing an issue with a web application that I am developing. On the left side of the page, there is an editable area, and on the right side, there is a live preview. The live preview area contains an HTML file with specific fields that can ...

Utilizing Vue.js components and properties to invoke a function

Trying to create a shopping cart button that keeps track of how many times it's clicked, but encountering an issue where the function called by the button doesn't receive the correct parameter. I attempted using {{id}} and :onClick="addThisToCar ...

Tips on toggling the visibility of div elements with JavaScript

In my selection block, I have three categories of elements and associated Divs. The goal is to display the related divs when a category is selected, while keeping them hidden otherwise. Specifically, I want the husband_name and number_pregnancy divs to be ...

Glistening tabPanel and Analytics by Google

I recently completed a comprehensive tutorial here that delves into the intricacies of Google Analytics. Despite grasping the concepts explained in the tutorial, my understanding of jQuery remains at ground zero. In my ShinyApp, I utilize multiple tabPanel ...

Validation of textfields using React.js

Currently, I am working on implementing a validation feature in ReactJS. Specifically, I have a field named "name" and my requirement is that every time a name is entered, it must be equal to or greater than 2 characters. The validation works fine when t ...

Setting up webpack encore for async and await in a Symfony 4 and VueJs project

After setting up a VueJs project within Symfony 4, I encountered an unexpected error involving await and async (Uncaught ReferenceError: regeneratorRuntime is not defined) I've come across plenty of resources for webpack, but nothing specifically for ...

Retrieving radio button value in Angular 2

Currently, I am attempting to retrieve the radio button value in an Angular 2 project. The radio buttons are defined in index.html as: <input type="radio" id="options1" name="function" value="create"> <input type="radio" id="options2" name="func ...

Tips for bringing in and taking out data in Vue

I have a set of files called total.vue and completeness.vue. I aim to display the chart from total.vue within completeness.vue, which is my designated admin dashboard where I plan to feature 2 or 3 additional charts. For this task, I will be exporting con ...

Reveal each element individually upon clicking the button

I am trying to display 5 div elements one by one when clicking a button, but the current code is not working. I am open to alternative solutions for achieving this. Additionally, I want to change the display property from none to flex in my div element. ...

Troubleshoot: Dropdown menu in Materialize not functioning (menu fails to drop down

I am currently incorporating Materialize to create a dropdown button in my navigation bar. However, I am facing an issue where nothing happens when the button is clicked. Here is a snippet of my code: <head> <meta charset="UTF-8"> <!-- ...

Using JavaScript to disable and re-enable an ASP.NET Timer control

I currently have a webpage built with ASP.Net that includes an ASP:Timer control <asp:Timer ID="TimerRefresh" runat="server" Interval="5000" Enabled="true" OnTick="TimerRefresh_Tick"> </asp:Timer> It is connected to an asp:UpdatePanel on the ...

I continue to encounter an error every time I attempt to place an HTML nested div on a separate line

When I structure the HTML like this, I don't encounter any errors: <div class="game-card"><div class="flipped"></div></div> However, if I format it differently, I receive an error message saying - Cannot set property 'vi ...

Sorting through various data inputs in one JSON file

I have a JSON file containing an array of objects: obj= [{fname:"abhi",age:5,class:"ten",lanme:"kumar" },{fname:"abhi",age:5,class:"ten",lanme:"kumar" },{fname:"abhi",age:5,class:"t ...

Checkbox acts like radio buttons in JavaScript

Currently, I have a unique setup where a table is generated dynamically based on the user's selection from a dropdown. Within this table are three checkboxes per row, with a limit of 2 checkboxes that can be checked per row. The behavior of Checkbox ...

Is it feasible to style individual letters in a word within an input field?

Is it possible to change the styling of individual letters in an input containing text? For example, if the word 'Test' is in the input, can I make the 'Te' bold while leaving the 'st' regular? Alternatively, perhaps I'd ...

The webpage is displaying an error stating that "<function> is not defined."

I recently duplicated a functional web page into a new file on my site. However, after adding a new function and removing some HTML code, the JavaScript function no longer runs when clicking one of the two buttons. Instead, I receive the error message "Beg ...

Using jQuery's ajax function to send data with a variable name of data field

I am trying to figure out how to dynamically add a variable to the name of the data field I want to send information to through ajax. Below is an example of the code I'm working on: var qty = $('#qty_'+value).val(); $.ajax({ url: &apo ...

Steps for creating a TypeScript project for exporting purposes

Forgive me for my lack of experience in the js ecosystem. Transitioning from static languages to typescript has been a positive change, though I still find myself struggling to grasp the packaging/module system, especially when coupled with typescript defi ...

Type Error: Issue encountered while resolving module specifier

Upon trying to import the d3.js library in a project that utilizes npm, I encountered the error message: TypeError: Error resolving module specifier: d3. This issue specifically occurred while using Firefox. index.html <!DOCTYPE html> <html lang ...

Challenges with cross domain iframes

I am trying to find a way to send a message from an iframe to the parent page at regular intervals, for example: Iframe Domain = www.abc.com Parent Domain = www.xyz.com I have looked into the following resources: Cross domain iframe issue If anyone ha ...