Skip to content

Document dynamic routing #261

Description

@thescientist13

Summary

In the next release, Greenwood will support dynamic routing for SSR pages and API routes, e.g.

Routing

src/
  pages/
    blog/
      [slug].js
    api/
      product/
        [id].js

SSR Page

export default class BlogPostPage extends HTMLElement {
  #slug: string;

  constructor({ params }) {
    super();
    this.#slug = params?.slug;
  }

  connectedCallback() {
    this.innerHTML = `
      <body>
        <h1>${this.#slug}</h1>
      </body>
    `;
  }
}

API Route

export async function handler(request: Request, { params }) {
  return new Response(`Product id is => ${params.id}`);
}

getStaticPaths / getStaticProps

import { getProducts } from '#src/services/products.js'

export async function getStaticPaths() {
  const products = await getProducts();

  return products.map((product) => {
    return {
      params: {
        id: product.id,
        name: product.name.replace(/ /g, "-").toLowerCase(),
      },
    };
  });
}

export async function getStaticParams({ params }) {
  const product = products.find((product) => product.id === params.id);

  return { product };
}

export async function getBody(compilation, request, page, params) {
  return `<h1>${params.product.name}</h1>`;
}

Additional Details

Things we need to document here - https://greenwoodjs.dev/docs/pages/routing/

Greenwood Issue

ProjectEvergreen/greenwood#882

Metadata

Metadata

Labels

docsGreenwood specific content like docs and guidesrelease/v0.34.0

Type

No fields configured for Task.

Projects

Status
👀 In review

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions