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
});Production builds also emit the Page Browser Graphs used by browser scripts and component dependencies. If those dependencies vary by route params, return every required route instance from staticPaths. ecopages start reuses the graphs in the build; a request that needs an unlisted graph fails instead of building it at request time. Development is unchanged.
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 the Node HTTP host, whether the process is Node or Bun. 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: Read API keys and configuration secrets from
process.envon the server.