Skip to content

Add fetch parameter to entries() for seamless API integration #12980

Open
@max-got

Description

@max-got

Describe the problem

The EntryGenerator's entries() function would benefit from having access to SvelteKit's enhanced fetch, enabling direct integration with API routes during the prerendering process.

Current Limitation:
Currently, when using the EntryGenerator pattern with dynamic routes that depend on API data, we need to duplicate the data fetching logic or import it directly from the filesystem. This is both less elegant and diverges from how we normally access data in SvelteKit applications.

Use Case:
Consider this setup:

// src/routes/api/items/+server.js
export async function GET() {
  // Returns prerendered API data
  return json(items);
}

// src/routes/items/[id]/+page.server.js
export const prerender = true;

/** @type {import('./$types').EntryGenerator} */
export async function entries({ fetch }) {  // <- Add fetch parameter
  // Can safely fetch from API routes
  const res = await fetch('/api/items');
  const items = await res.json();
  
  return items.map(item => ({
    id: item.id
  }));
}

export async function load({ fetch, params }) {
  const res = await fetch(`/api/items/${params.id}`);
  const item = await res.json();
  return { item };
}

Benefits:

  • Consistent data fetching pattern across load and entries functions
  • Reuse existing API routes for entry generation
  • Keep data fetching logic DRY
  • Works seamlessly with SvelteKit's prerendering system

Describe the proposed solution

/** @type {import('./$types').EntryGenerator} */
export async function entries({ fetch }) {
  // Now we can use the same fetch as in load functions
  const res = await fetch('/api/items');
  const items = await res.json();
  return items.map(item => ({ id: item.id }));
}

Alternatives considered

  • Manual data imports: Less maintainable, duplicates logic
  • Direct filesystem access: Breaks the API abstraction, less portable
  • Custom fetch implementation: Unnecessary given SvelteKit's existing fetch capabilities

Importance

would make my life easier

Additional Information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions