Server-Side Data Fetching
Analog supports fetching data from the server before loading a page. This can be achieved by defining an async load
function in .server.ts
file of the page.
Setting the Public Base URL
Analog requires the public base URL to be set when using the server-side data fetching. Set an environment variable, using a .env
file to define the public base URL.
// .env
VITE_ANALOG_PUBLIC_BASE_URL="http://localhost:5173"
The environment variable must also be set when building for deployment.
Fetching the Data
To fetch the data from the server, create a .server.ts
file that contains the async load
function alongside the .page.ts
file.
// src/app/pages/index.server.ts
import { PageServerLoad } from '@analogjs/router';
export const load = async ({
params, // params/queryParams from the request
req, // H3 Request
res, // H3 Response handler
fetch, // internal fetch for direct API calls,
event, // full request event
}: PageServerLoad) => {
return {
loaded: true,
};
};