Jeasx is a server-side rendering (SSR) framework based on JSX, which means that all of your code is executed on the server and the resulting HTML is sent to the client. JSX is a great templating technology due to its simplicity if you are familiar with the basics of JavaScript.

If you are not familiar with JSX, you should read the excellent introduction to JSX at the React homepage.

JSX in Jeasx is a little bit different

Jeasx uses a syntax similar to React, but there are some important differences. Under the hood an independent asynchronous JSX runtime implementation (jsx-async-runtime) is used, which is optimized for performant server-side rendering. As this runtime is mostly intended for creating HTML markup on a server, it tries to stick as close to the HTML standards as possible.

  • You can use asynchronous code out of the box: mark your component as async and use await to resolve promises. You can also pass promises directly as children or attribute values (e.g. <div>{fetchUser()}</div> or <img src={loadImageUrl()} />).
  • Attribute names are the same as in HTML, therefore you must use class instead of className or aria-label instead of ariaLabel.
  • The class and style attributes must be strings. Objects and arrays are not converted to class lists or CSS, but rendered as JSON like any other attribute (see below), so use a helper like clsx for conditional classes (e.g. <h1 class={clsx("center", { active })} style="color: red; margin-top: 1rem">...</h1>).
  • children are passed as written: a single child as is, several children as an array, and no children prop at all without children. Normalize with [children ?? []].flat() before calling array methods.
  • Iterables (e.g. Set or generators), async iterables and ReadableStream can be used as children. They are rendered in order as items arrive.
  • Pages are streamed to the browser while they are still rendering, so the browser receives the first bytes while slow parts of the page (e.g. awaited data) are still loading.
  • When using an object as value for an attribute, it is translated to a JSON string in the resulting markup (e.g. data-props={{ key: "value" }} becomes data-props="{&quot;key&quot;:&quot;value&quot;}").

HTML is escaped by default

With Jeasx all HTML markup is escaped by default. If you want to include HTML (or other code) snippets, wrap the literal code with the html() function from jsx-async-runtime: {html("<p>Some HTML from a CMS</p>")}.

import { html } from "jsx-async-runtime";

<>
  {html("<!DOCTYPE html>")}
  <html lang="en">
    <body>
      <h1>{html("Include <i>literal</i> html from a <b>trusted</b> source")}</h1>
    </body>
  </html>
</>;

Escaping can't be turned off. Only markup created by html() is rendered raw, so use it for trusted sources only. Objects that just look like markup (e.g. { html: "..." } from parsed JSON) render nothing.

This also applies to the content of <script> and <style> tags: it is escaped like any other text, so <style>{"a > b {}"}</style> renders a &gt; b {}, which breaks your CSS. Wrap inline scripts and styles in html():

<style>{html("a > span { color: red; }")}</style>
<script>{html("if (a < b) { console.log('ok'); }")}</script>

Never put untrusted input into inline scripts or styles. To pass data to browser code, use a data-* attribute instead (see CSS & JavaScript).

If you need to escape HTML by hand, you can import the utility function from jsx-async-runtime:

import { escapeEntities } from "jsx-async-runtime";

escapeEntities("<p>Hello World</p>");

Here's an example which shows the differences in a single file

import { html } from "jsx-async-runtime";

export default async function () {
  const { value } = await (await fetch("https://api.chucknorris.io/jokes/random")).json();

  return (
    <>
      {html("<!DOCTYPE html>")}
      <html lang="en">
        <head>
          <title>Jokes</title>
          <style>{html(".center {text-align: center;}")}</style>
        </head>
        <body class="body" style="background-color: red; padding: 1rem">
          <div class="v-align h-align" data-props={{ key: "value" }}>
            <h1 class="center my-class" style="color: white">
              {value}
            </h1>
          </div>
        </body>
      </html>
    </>
  );
}

View the result of the above code

Transforming JSX components at runtime

The JSX runtime also provides a way to transform JSX components. This can be useful to patch the markup of 3rd party components or to rewrite existing attributes of components.

The following example adds a revision to all image sources, so each image receives a new URL with each deployment. It works by adding a custom jsxToString handler via the this context. The handler receives every node that is rendered (elements, text, null, ...), so check for elements with isJsxNode before changing them. Just add the following code as src/[...guard].js to your project:

import { isJsxNode, jsxToString } from "jsx-async-runtime";

const REVISION = Date.now().toString(36);

export default function ({ request, reply }) {
  this.jsxToString = (jsxElement) => {
    if (isJsxNode(jsxElement) && jsxElement.tag === "img") {
      jsxElement.props.src = jsxElement.props.src + "?" + REVISION;
    }
    return jsxToString.call(this, jsxElement);
  };
}

Please note: an override renders everything below it to a string, so the affected part of the page is sent as one chunk instead of being streamed. An override set in a root guard (like above) turns off streaming for the whole page, so only use overrides where you really need them. For cache busting of your own assets, a build id is simpler and keeps streaming intact (see cache busting).

Learn more

For all the advanced features provided by the jsx-async-runtime, have a look at the example application in the GitHub-Repository.

Sharing data via the context

Jeasx provides a context object via this, which is passed on to all sub-components automatically, similar to the context in React. Every request gets its own context. You can populate it in an endpoint (e.g. a guard):

export default function ({ request, reply }) {
  this.date = new Date();
}

A common pattern is to put the request and reply into the context in your root guard (src/[...guard].js), so every component can read e.g. this.request.path or log via this.request.log:

export default function ({ request, reply }) {
  this.request = request;
  this.reply = reply;
}

Later, you can access the context in any sub-component which gets called via an endpoint:

export default function () {
  return <p>The current date is {this.date.toISOString()}</p>;
}

Have a look at the demo to see how things work using the context as theme provider.

Please note: this only works in components declared with function. Arrow functions don't have their own this, so const Nav = () => <a>{this.request.path}</a> fails. Also render components as JSX (<Nav />) instead of calling them directly (Nav()), otherwise they don't receive the context.

To get type hints for your context in your editor, describe it in src/types.d.ts (see TypeScript) and annotate your components with @this:

/**
 * @this {import("./types").ThisContext}
 */
export default function Nav() {
  return <a href="/" aria-current={this.request.path === "/" ? "page" : undefined}>Home</a>;
}

Special context properties

You can put anything into the context. A few names have a special meaning for Jeasx:

PropertyPurpose
this.jsxToStringCustom render function to transform JSX nodes (see transforming JSX)
this.responseHandlerReceives the final payload of the route and returns the payload to send, e.g. to post-process HTML (see FAQ)
this.request / this.replyNot set by Jeasx, but a common convention: put them into the context in your root guard to use them in every component

MDX: Markdown for the component era

MDX allows you to use JSX directly within your markdown content. This means you can import JSX components and seamlessly embed them in your text. This makes writing long-form content with dynamic components much more enjoyable and efficient. Markdown often feels more natural to write than HTML or JSX, especially for common elements like emphasis or headings.

A good example for a Jeasx website powered by MDX is this website. Have a look at GitHub to see how things are wired up.

If you want to use MDX with Jeasx, simply run npm install @mdx-js/esbuild and add the configuration below to ESBUILD_SERVER_OPTIONS in jeasx.config.js.

Build plugins should be loaded lazily via dynamic import() inside the config function, as shown below. This way they are only loaded when esbuild actually needs them, which keeps the server startup time short.

export default {
  /** @type {() => Promise<import("esbuild").BuildOptions>} */
  ESBUILD_SERVER_OPTIONS: async () => {
    const { default: mdx } = await import("@mdx-js/esbuild");
    return {
      plugins: [
        mdx({
          development: process.env.NODE_ENV === "development",
          jsxImportSource: "jsx-async-runtime",
          elementAttributeNameCase: "html",
          stylePropertyNameCase: "css",
        }),
      ],
    };
  },
};

Then simply create a route with the .mdx extension and begin writing markdown. You can import and use existing JSX components right inside your markdown content. Conversely, it's also possible to import MDX components into JSX files.

Please note: to access props in MDX, you have to use props as explicit namespace (e.g. props.request.path).

import Layout from "./Layout"

{/** @typedef {import("./types").RouteProps} Props */}

<Layout title="MDX is the perfect companion for JSX">
# Heading 1
## Heading 2
### ...

> Block quote

- Unordered
- List

1. Ordered
2. List

A paragraph, introducing a thematic break:

---

You can easily access existing `props` in MDX:

- Path: {props.request.path}
- Route: {props.request.route}
</Layout>

Jeasx supports this as context for JSX components. This is not supported in MDX. As a workaround, you can wire up a route guard and submit this as additional prop for all guarded routes. Then you can access this via props.this in MDX.

export default function ({ request, reply }) {
  return { this: this };
}

If you want to configure additional MDX plugins, install them in your project first (e.g. npm install rehype-prism-plus rehype-slug remark-gfm) and add them to your jeasx.config.js. Jeasx uses @mdx-js/esbuild under the hood to transform MDX to JSX, so have a look at the documentation for existing plugins and configurations.

export default {
  /** @type {() => Promise<import("esbuild").BuildOptions>} */
  ESBUILD_SERVER_OPTIONS: async () => {
    const [
      { default: mdx },
      { default: rehypePrismPlus },
      { default: rehypeSlug },
      { default: remarkGFM },
    ] = await Promise.all([
      import("@mdx-js/esbuild"),
      import("rehype-prism-plus"),
      import("rehype-slug"),
      import("remark-gfm"),
    ]);
    return {
      plugins: [
        mdx({
          development: process.env.NODE_ENV === "development",
          jsxImportSource: "jsx-async-runtime",
          elementAttributeNameCase: "html",
          stylePropertyNameCase: "css",
          remarkPlugins: [[remarkGFM, { singleTilde: false }]],
          rehypePlugins: [rehypePrismPlus, [rehypeSlug, { prefix: "jeasx-" }]],
        }),
      ],
    };
  },
};