skip to Main Content

I was trying to access the full URL to prepare the page head in sveltekit,

I tried window.location.origin but then SvelteKit has a 500 error with ReferenceError: window is not defined

<svelte:head>
  <!-- Set Hreflang for SEO https://developer.chrome.com/docs/lighthouse/seo/hreflang/ -->
  <link rel="alternate" hreflang="en" href="{window.location.origin}" />
</svelte:head>

2

Answers


  1. Chosen as BEST ANSWER

    You can access the full URL from the server side this way :

    <script>
    import { page } from '$app/stores'
    </script>
    
    <svelte:head>
      <!-- Set Hreflang for SEO https://developer.chrome.com/docs/lighthouse/seo/hreflang/ -->
      <link rel="alternate" hreflang="en" href="{$page.url.href}" />
    </svelte:head>
    

  2. On the server side, you’ll need to use url.href.

    For example, in +page.server.ts:

    export const load: PageServerLoad = async ({ url }) => {
        const href = url.href;
        ...
    }
        
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search