Home >Web Front-end >JS Tutorial >How to use Astro with Hono
Astro: A powerful web framework, my current favorite. Its versatility makes it ideal for a wide range of projects. However, for API development, Hono stands out.
Hono: A simple, portable API framework with a user-friendly RPC system (resembling tRPC but faster). This guide shows how to combine the strengths of both.
Setting up Astro
Create a new Astro project using:
<code class="language-bash">npm create astro@latest</code>
Follow the CLI prompts. Start the project with:
<code class="language-bash">npm run dev</code>
Access your Astro project at http://localhost:4321
.
Setting up Hono
Install Hono:
<code class="language-bash">npm install hono</code>
Create a catch-all route in src/pages/api/[...path].ts
:
<code class="language-typescript">// src/pages/api/[...path].ts import { Hono } from 'hono'; const app = new Hono().basePath('/api/'); app.get('/posts', async (c) => { return { posts: [ { id: 1, title: 'Hello World' }, { id: 2, title: 'Goodbye World' }, ], }; }); </code>
The .basePath('/api/')
is crucial; it aligns Hono's routing with Astro's file structure. Adjust this path as needed to match your Astro project's endpoint location (e.g., /foo/bar/
for src/pages/foo/bar/[...path].ts
).
Integrating Hono with Astro
Create an ALL
export to handle all requests and route them to Hono:
<code class="language-typescript">// src/pages/api/[...path].ts import { Hono } from 'hono'; import type { APIRoute } from 'astro'; // ... (Hono app setup from previous step) ... export type App = typeof app; // Export Hono app type export const ALL: APIRoute = (context) => app.fetch(context.request);</code>
Now, http://localhost:4321/api/posts
will return your mock data via Hono.
Adding a Typed RPC Client
For type-safe API interactions, use Hono's hc
client:
<code class="language-typescript">// src/pages/some-astro-page.astro import { hc } from 'hono/client'; import type { App } from './api/[...path].ts'; const client = hc<App>(window.location.href); const response = await client.posts.$get(); const json = await response.json(); console.log(json); // { posts: [...] }</code>
Conclusion
This setup combines Astro's frontend power with Hono's efficient backend capabilities, providing a streamlined development experience with type safety. Explore Hono's extensive features for even more advanced API development.
The above is the detailed content of How to use Astro with Hono. For more information, please follow other related articles on the PHP Chinese website!