Data Fetching
Ecopages provides built-in functions for fetching data at build time (for static generation) and at runtime (via API handlers).
Build-Time Data Fetching
When generating static pages, use the eco.page factory to provide data to your components.
staticProps
Injects custom props into your page component at build time.
import { eco } from '@ecopages/core';
export type PageProps = { title: string; content: string };
export default eco.page<PageProps>({
staticProps: async () => {
// Fetch data from a database, file, or external API
const data = await fetch('https://api.example.com/page-data').then(res => res.json());
return {
props: {
title: data.title,
content: data.content,
},
};
},
render: ({ title, content }) => (
<>
<h1>{title}</h1>
<div>{content}</div>
</>
),
});staticPaths
Required for dynamic routes ([param]). It tells Ecopages which paths should be pre-rendered.
import { eco } from '@ecopages/core';
export default eco.page({
staticPaths: async () => {
const posts = await getAllPosts();
return {
paths: posts.map((post) => ({ params: { slug: post.slug } })),
};
},
// ... rest of page config
});Runtime Data Fetching
For dynamic applications, you can fetch data directly from your client-side scripts or through Ecopages API handlers.
Fetching from API Handlers
Ecopages API handlers run on your configured server adapter (for example Bun or Node). They are perfect for proxying requests or interacting with a database.
// app.ts
app.get('/api/users/:id', async ({ params, response }) => {
const user = await db.users.find(params.id);
return response.json(user);
});Client-Side Fetching
Standard browser fetch works as expected inside your *.script.ts files or hydrated components (React/Lit).
Best Practices
- Direct Calls: Inside
staticProps, prefer direct function calls (e.g.,db.query()) rather than calling your own API routes via HTTP to improve build performance. - Type Safety: The
eco.pagefactory provides automatic type inference for your component props based on the return type ofstaticProps. - Environment Variables: Use
import.meta.envto access API keys and configuration secrets safely.