hono.js+react实现短链生成

● 2026.07.246 min read
hono.js+react实现短链生成

使用honojs和react的理由

使用honojs原因是honojs是现代js后端框架中较新的一种,性能高,体积小,(虽然没有什么企业在用,企业还在用老古董express),使用正则匹配路由,号称js框架中最快的路由匹配(主要还是对cloudflare的支持比较好,甚至还支持不同的运行时),使用react的理由是单纯我想用,因为hono可以直接返回jsx,tsx,但是我就是要前后端分离(bushi),这样方便管理,不像nextjs一样像一坨屎聚在一起,虽然用honoX做SSR和全栈一样屎,hono这时高性能的优势就体现出来了

后端使用的相关package

zod

用于校验入参是否为http

z.object({ url: z.string().url("无效的url格式") });

zod提供了直接对入参进行url校验的方法,甚至连校验错误返回的信息都封装好了,不需要自己写try-catch 如果你想进一步校验,比如只允许https,可以使用ts官方的api startsWith(),也是比较方便的。

nanoid

一键生成短链,方便好用

const shorten = nanoid(6);

实现的主要接口

app.post('/api/shorten', async (c) => {
   const body = await c.req.json();
   const url = shortenSchema.safeParse(body);
   if(!url.success){
      return c.json({error: url.error.issues[0]?.message || '请求参数错误'}, 400);
   }
   const validUrl = url.data.url;
   const shortCode = nanoid(6);
   await c.env.KV.put(shortCode, validUrl);
   const shortUrl = `https://${c.env.SHORT_DOMAIN}/${shortCode}`;
   return c.json({shortUrl});

})

app.get('/:code', async (c) => {
   const code = c.req.param('code');
   const url = await c.env.KV.get(code);
   if(!url) {
      return c.text("链接不存在",404);
   }
   return c.redirect(url, 302);
})