Skip Navigation

Scott Spence

Passing SvelteKit +page.server.ts data to +page.ts

2 min read

I came across this issue when adding real-time analytics to my site, essentially what I wanted to do was get some analytics data from a server endpoint and pass that to the page.

In SvelteKit you can have different ways to get data onto a page, which I’ve detailed it in the past, what I didn’t cover then was what do you do when you have both a +page.server.ts and a +page.ts file returning data.

The +page.server.ts will run first then then pass anything down to the +page.ts (child) file, let’s look at a super simple example. I’ll have a +page.server.ts and a +page.ts files that both return the some data.

First the +page.server.ts file:

import type { PageServerLoad } from './$types'

export const load: PageServerLoad = async () => {
  return {
    page_server_data: { message: 'hello world' },
  }
}

Then the +page.ts file:

import type { PageLoad } from './$types'

export const load: PageLoad = async ({ parent, data }) => {
  await parent()
  let { page_server_data } = data
  return {
    page_server_data,
    page_data: { message: 'hello world' },
  }
}

In the +page.ts file we can access the data and the parent the (+page.server.ts file) then await the parent to get the data from the +page.server.ts file.

On the +page.svelte file we can access the data from both files:

<script lang="ts">
  import type { PageData } from './$types'

  export let data: PageData
</script>

<pre>{JSON.stringify(data, null, 2)}</pre>

Output:

{
  "page_server_data": {
    "message": "hello world"
  },
  "page_data": {
    "message": "hello world"
  }
}

This is the same approach if you’re doing this with a +layout.server.ts and +layout.ts files.

Hope this helps anyone who comes across this.

There's a reactions leaderboard you can check out too.

Analytics Information

Daily analytics for this post

Views Today
4
Sep 28, 2023 2:36 PM
Visitors Today
4
Sep 28, 2023 2:36 PM
Entries Today
4
Sep 28, 2023 2:36 PM

Monthly analytics for this post

Views This Month
375
Sep 1, 2023 - Sep 28, 2023
Visitors This Month
239
Sep 1, 2023 - Sep 28, 2023
Entries This Month
236
Sep 1, 2023 - Sep 28, 2023

Yearly analytics for this post

Views This Year
2.3k
Jan 1, 2023 - Sep 28, 2023
Visitors This Year
1.4k
Jan 1, 2023 - Sep 28, 2023
Entries This Year
1.3k
Jan 1, 2023 - Sep 28, 2023

Copyright © 2017 - 2023 - All rights reserved Scott Spence