v 0.1.97

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 ({ pathname }) => {
        // 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 }) => html`
        <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 the Bun server. They are perfect for proxying requests or interacting with a database.

// app.ts
app.get('/api/users/:id', async ({ request, response }) => {
    const user = await db.users.find(request.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

  1. 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.
  2. Type Safety: The eco.page factory provides automatic type inference for your component props based on the return type of staticProps.
  3. Environment Variables: Use import.meta.env to access API keys and configuration secrets safely.