Redirecting after a POST with Hono and HTMX

Nov 2023
tags:honohtmx

Often you will want to redirect somewhere after a form is submitted. For instance, after creating a new blog post, you may want to redirect to a review route.

In your Hono route, you can simply return a 204 response without a body:

app.post('/create-post', async (c) => {
  const formData = await c.req.formData();

  // await doSomethingWithTheFormData(formData)

  c.status(204);
  return c.body(null)
});

To tell HTMX to redirect to a certain screen, you can use the HX-Redirect header:

app.post('/create-post', async (c) => {
  const formData = await c.req.formData();

  const { id } = await doSomethingWithTheFormData(formData)

  c.header("HX-Redirect", `/review/${id}`);
  c.status(204);
  return c.body(null)
});