Skip to main content

Routes

Root.js uses filesystem based routing similar to Next.js. Routes are defined within the routes/ folder and render TSX files as server-rendered components.

Below are a few examples of routes files and the final serving path:

Route Matching URL(s)
@/routes/index.tsx /
@/routes/about.tsx /about
@/routes/blog/index.tsx /blog
@/routes/blog/[slug].tsx
  • /blog/foo
  • /blog/bar

Page

The route's default export is automatically rendered as a TSX server component.

Example:

tsx
// @/routes/index.tsx

export default function Page() {
  return <h1>Hello, world!</h1>
}

If you need to fetch data to pass to your Page component, you can export a function called getStaticProps() (SSG) or handle() (SSR) from your route file. See more below.

getStaticProps()

If a exported function called getStaticProps exists in the route, the props returned from that function will be passed to the component.

Routes that use placeholder params like [slug].tsx will have these params passed into a context variable to getStaticProps().

Example:

tsx
// @/routes/[slug].tsx

import {GetStaticProps} from '@blinkk/root';

export default function Page(props) {
  console.log('db content: ', props.content);
  return <h1>The slug is {props.slug}</h1>;
}

export const getStaticProps: GetStaticProps = async (ctx) => {
  const slug = ctx.params.slug;
  const content = await fetchDataFromDatabase(slug);
  return {props: {slug, content}};
};

getStaticPaths()

For routes that use placeholder params, projects that build sites using SSG will need to deterministically know what paths are available for that route. Export a getStaticPaths() function in the route and return a list of params.

Example:

tsx
// @/routes/[slug].tsx

import {GetStaticPaths} from '@blinkk/root';

export default function Page(props) {
  return <h1>hello world</h1>;
}

export const getStaticPaths: GetStaticPaths = async (ctx) => {
  const slugs = await listAllFromDb(slug);
  return {paths: slugs.map((slug) => {params: {slug}})};
};

handle()

For routes that prefer to run in SSR mode, you can export a function called handle() that is similar to an Express.js request handler. Use req.ctx.render() to render the route's Page component.

tsx
// @/routes/[slug].tsx

import {Handler, HandlerContext} from '@blinkk/root';

export default function Page(props) {
  const name = props.name || 'World';
  return <h1>Hello, {name}!</h1>;
}

export const handle: Handler = async (req, res) => {
  const name = req.query.name;
  const ctx = req.handlerContext as HandlerContext;
  return ctx.render({name: name});
};

404.tsx

To define a custom 404 page, add a route at routes/404.tsx. On prod, that route will be rendered when no other route matches the given request.

1
2
3
4
5
6
7
8
9
10
11
12
Breakpoint: