Servers
server.jsread-only
const { Hono } = require('hono');
const app = new Hono();

const users = [
  { id: 1, name: 'Alice Johnson', email: 'alice@example.com', role: 'admin' },
  { id: 2, name: 'Bob Smith', email: 'bob@example.com', role: 'user' },
  { id: 3, name: 'Charlie Brown', email: 'charlie@example.com', role: 'user' },
];

// -- Middleware: Logger --
app.use('*', async (c, next) => {
  const start = Date.now();
  console.log('--> ' + c.req.method + ' ' + c.req.path);
  await next();
  const ms = Date.now() - start;
  c.header('X-Response-Time', ms + 'ms');
  console.log('<-- ' + c.req.method + ' ' + c.req.path + ' ' + c.res.status + ' ' + ms + 'ms');
});

// -- Middleware: CORS --
app.use('*', async (c, next) => {
  await next();
  c.header('Access-Control-Allow-Origin', '*');
  c.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
});

// -- Middleware: Request ID --
app.use('*', async (c, next) => {
  const id = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(ch) {
    var r = Math.random() * 16 | 0;
    return (ch === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  });
  c.set('requestId', id);
  await next();
  c.header('X-Request-Id', id);
});

// -- Routes --
app.get('/', (c) => {
  return c.json({
    name: 'Hono API',
    version: '1.0.0',
    middleware: ['logger', 'cors', 'request-id'],
    endpoints: ['/api/users', '/api/time', '/api/random'],
  });
});

app.get('/api/users', (c) => {
  return c.json(users);
});

app.get('/api/users/:id', (c) => {
  const id = Number(c.req.param('id'));
  const user = users.find(u => u.id === id);
  if (user) return c.json(user);
  return c.json({ error: 'User not found' }, 404);
});

app.get('/api/time', (c) => {
  return c.json({
    timestamp: Date.now(),
    iso: new Date().toISOString(),
    readable: new Date().toLocaleString(),
    requestId: c.get('requestId'),
  });
});

app.get('/api/random', (c) => {
  return c.json({
    number: Math.random(),
    dice: Math.floor(Math.random() * 6) + 1,
    uuid: 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(ch) {
      var r = Math.random() * 16 | 0;
      return (ch === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    }),
    requestId: c.get('requestId'),
  });
});

globalThis.__app = app;
console.log('Hono server ready (3 middleware active)');
API Explorer

Select a route above to test it

Responses are processed in the virtual runtime

Terminal
$

A Hono web framework server running in the browser with composable middleware, including logger, CORS, and request ID generation. Uses the same interactive API explorer as the Express example.

Details

Things to try

  1. Use the API explorer to test different endpoints
  2. Watch the terminal for middleware logs (logger output)
  3. Check response headers for CORS and request ID values