honojs / examples Goto Github PK
View Code? Open in Web Editor NEWExamples using Hono.
Home Page: https://hono.dev
Examples using Hono.
Home Page: https://hono.dev
How can you encrypt keys to later validate with jwt, I tried with bcrypt but it gave me errors
Do you have any relevant examples?
I have been trying to use Hono and JsDoc Comments as JSDoc just improves how we use Javascript and is really helpful, I work on solo projects not someone who like typescript in that regards and using Cloudflare workers I have been encountering issues such as
X [ERROR] Could not resolve "hono/dist/types"
src/workers/handlers/Auth.Handler.js:4:24:
4 │ import { Context } from "hono/dist/types";
╵ ~~~~~~~~~~~~~~~~~
The path "./dist/types" is not exported by package "hono":
node_modules/hono/package.json:36:13:
36 │ "exports": {
╵ ^
The file "./dist/types.js" is exported at path "./types":
node_modules/hono/package.json:44:16:
44 │ "import": "./dist/types.js",
╵ ~~~~~~~~~~~~~~~~~
Import from "hono/types" to get the file "node_modules/hono/dist/types.js":
src/workers/handlers/Auth.Handler.js:4:24:
4 │ import { Context } from "hono/dist/types";
│ ~~~~~~~~~~~~~~~~~
╵ "hono/types"
You can mark the path "hono/dist/types" as external to exclude it from the bundle, which will remove this error.
When I do hono/types it rather goes on fetching hono/dist/types.js something I do not want
I would really like the support for JSDoc as I use it too much and this library is really helpful, Below attached output
src/workers/handlers/Auth.Handler.js:4:9:
4 │ import { Context } from "hono/types";
╵ ~~~~~~~
I would also be glad to know if somehow I can contribute to this repository in this regard if the feature is still not implemented, If it is I would be glad to know
Hi, I'm newer to hono and cloudflare workers. In the jsx-ssr example, I add some code to get value from the KV storage.
A error happens: TypeError: Cannot read properties of undefined (reading 'get')
.
And I out put the c.env
and it is empty: {}
.
Is there something wrong?
Hi,
Good job on Hono!
Followed this hono-example-blog example.
The route will become /post/post, not /post.
Index.ts should have this instead, think it would fix it.
app.route('/', middleware)
app.route('/', api)
Am I wrong? Please explain to me in that case how you're suppose to you app.route correct.
First off, have to say I've really been enjoying working with Hono. It's delivered on everything I've asked of it so far and has done so with ease, with this issue being the only exception (and possibly not due to Hono at all).
In the Stripe Webhook Example docs, when I use the code as defined, the Stripe Verification function fails. This seems to be an issue with the request body
, though, the error I get states it's to do with the signature
(seems the error's a bit coarse – I've verified that there's no trailing whitespace in the signature, debug attempts detailed below). Here's the full error:
⚠️ Webhook signature verification failed. No signatures
found matching the expected signature for payload. Are
you passing the raw request body you received from Stripe?
If a webhook request is being forwarded by a third-party tool,
ensure that the exact request body, including JSON
formatting and new line style, is preserved.
Learn more about webhook signing and explore webhook
integration examples for various frameworks at
https://github.com/stripe/stripe-node#webhook-signing
Note: The provided signing secret contains whitespace.
This often indicates an extra newline or space is in the value
I've tried a variety of things to get the verification working:
context.req.text()
, context.req.raw.text()
, context.req.body()
.This seems to be an issue with how Hono is processing the body of the request. If others can get this working in a different runtime, however, it may be that the Deno runtime of Supabase Functions is modifying the body (from what I've seen in my other edge functions, this isn't the case. Still, I haven't completely ruled it out).
All said, how can I get Stripe Webhook Verification working? And is the example in the docs current or does it need to be updated?
Any insights appreciated – thanks!
In case it helps:
Relevant entries from import_map.json
.
"imports": {
"@deno/server": "https://deno.land/[email protected]/http/server.ts",
"@hono": "https://esm.sh/v135/[email protected]",
"@stripe": "https://esm.sh/[email protected]?target=deno"
}
index.ts
)import { Hono } from "@hono";
// All Middleware Imports Removed
import type { Context } from "@hono";
// Routes
import stripe from './routes/stripe.ts';
/*
Get Mode
*/
const mode = Deno.env.get("MODE");
/*
Initialize API
*/
const api = new Hono({ strict: true }).basePath("/webhooks");
/*
Initialize Middlewares
*/
// All Middleware Instantiations Removed
/*
Set Controller Routes
*/
api.route("/stripe", stripe);
// Serve API
Deno.serve(api.fetch);
/routes/stripe.ts
)import { Hono } from '@hono';
import { Stripe } from "@stripe";
import type { Context } from "@hono";
// Initialize Hono Routes
const routes = new Hono();
routes.on("POST", "/event/payment-intent-state-change", async (context: Context) => {
const STRIPE_SECRET_KEY = Deno.env.get("STRIPE_SECRET_KEY") ?? "";
const STRIPE_API_VERSION = Deno.env.get("STRIPE_API_VERSION") ?? "2023-10-16";
const STRIPE_WEBHOOK_SECRET = Deno.env.get("STRIPE_PAYMENT_INTENT_WEBHOOK_SECRET") ?? "";
const stripe = new Stripe(STRIPE_SECRET_KEY, {
apiVersion: STRIPE_API_VERSION,
httpClient: Stripe.createFetchHttpClient(),
});
try {
const body = await context.req.text();
const signature = context.req.header('stripe-signature');
if (!signature) {
return context.text('Status: Webhook Error – Signature not found', 400);
}
if (!body) {
return context.text('Status: Webhook Error – Event not found', 400);
}
const event = await stripe.webhooks.constructEventAsync(
body,
signature,
STRIPE_WEBHOOK_SECRET,
undefined,
Stripe.createSubtleCryptoProvider(),
);
// Handle the event
switch (event.type) {
case 'payment_intent.succeeded': {
const paymentIntent = event.data.object;
console.log(`Status: Payload Verified – PaymentIntent for ${paymentIntent.amount} was successful!`);
// Then define and call a method to handle the successful payment intent.
// handlePaymentIntentSucceeded(paymentIntent);
break;
}
default: {
// Unexpected event type
console.log(`Status: Webhook Error – Unhandled event type ${event.type}.`);
}
}
} catch (error) {
const message = error instanceof Error ? error.message : 'Internal server error';
return context.text(`Status: Webhook Error – ${message}`, 400);
}
// Return a 200 response to acknowledge receipt of the event
return context.text('Status: Webhook Success', 200);
});
export default routes;
@yusukebe , is there an interest in my adding another blog type web app in the examples folder?
The current is api based, while the one I have renders html using simple interpolated strings.
the app also uses postgres for the data.
TypeError [ERR_INVALID_ARG_TYPE]: The "strategy" argument must be of type object. Received type number (0)
at new ReadableStream (node:internal/webstreams/readablestream:254:5)
at safeReadableStreamFrom (/Users/hongling/hands-dirty/hono/examples/node_modules/miniflare/dist/src/index.js:8358:10)
at #handleLoopback (/Users/hongling/hands-dirty/hono/examples/node_modules/miniflare/dist/src/index.js:8520:36)
at Server.emit (node:events:531:35)
at parserOnIncoming (node:_http_server:1137:12)
at HTTPParser.parserOnHeadersComplete (node:_http_common:119:17) {
code: 'ERR_INVALID_ARG_TYPE'
}
Are there any example of modern-monorepo-stack (pnpm and turborepo) using Hono RPC?
If not, I want to add!
Did this still the type of client is unkonw. Ran pnpm install and restrated the server.
@yusukebe Is it possible to use Hono with the new Next.js app directory? If so, do you have some example?
Thank you for your excellent work
Hey,
I really like hono, and I'd love to see how I can use it with cloudflare queue ? And Cron ?
Maybe some simple example would be super nice
A full example
It does a whole bunch of stuff like support oauth, email sending using Amazon SES, permissions, rate limiter using durable objects, SQL database using PlanetScale
https://github.com/OultimoCoder/cloudflare-planetscale-hono-boilerplate
It might be worth linking to as a larger example? But if not don't worry about it.
I found a mistake in the usage commands.
This command does not work.
Lines 25 to 27 in 284f11c
-yarn run install
+yarn install
Hello Hono Maintainers,
I am the creator of a code-first server framework called Pylon for building GraphQL APIs. Pylon simplifies the process by allowing developers to define any TypeScript functions, which Pylon then analyzes to automatically generate a GraphQL API. This approach eliminates the need to write any schema.
I believe it would be beneficial to include an example project in the Hono repository to demonstrate how Pylon leverages Hono and how it can be extended directly with Hono.
This example project would serve as a starter kit for building GraphQL APIs with Hono in an easy and streamlined manner using Pylon. I think this integration could greatly benefit both the Hono and Pylon communities by providing a practical, ready-to-use example.
For more details on how Pylon uses Hono, you can refer to the Pylon documentation and the specific Hono integration section.
If you are interested, I would be happy to prepare and submit a pull request with the example implementation.
Thank you for your consideration.
I am using hono
(v3.12.6) in some personal projects lately, it is simple and fun, but when it comes to file handling, I am having some trouble and was not able to figure it out.
I followed the instructions here
but with no results :
// ... handlers
.post('/:id/file', async (ctx: AppAuthContext) => {
const user = ctx.get('user');
const projectId = ctx.req.param('id');
const parsed = await ctx.req.parseBody();
const file = parsed['file'] as File;
const form = await ctx.req.formData();
const body = {
type: form.get('type') as ProjectType,
};
const json = await createProjectFile(user, projectId, file, body);
return ctx.json(json);
});
and this is my postman request :
Maybe this is not the correct place for this issue, but I think that a clear example can prevent a lot of headaches.
Thank you.
In the blog example you can use getMiniflareBindings()
to get access to the global env variables. I am trying to do the same thing in my project but can't replicate the functionality.
bindings.d.ts file:
export interface Bindings {
ENV: string
MYSQL_URL: string
JWT_SECRET: string
JWT_ACCESS_EXPIRATION_MINUTES: number
JWT_REFRESH_EXPIRATION_DAYS: number
JWT_RESET_PASSWORD_EXPIRATION_MINUTES: number
JWT_VERIFY_EMAIL_EXPIRATION_MINUTES: number
}
declare global {
function getMiniflareBindings(): Bindings
}
Trying to use it:
const env = getMiniflareBindings()
Error:
ReferenceError: getMiniflareBindings is not defined
build.js:
import { build } from 'esbuild'
try {
await build({
entryPoints: ['./src/index.ts'],
bundle: true,
outdir: './dist/',
sourcemap: true,
minify: true
})
} catch(err) {
process.exitCode = 1;
}
tsconfig.json:
{
"compilerOptions": {
"allowJs": true,
"target": "esnext",
"lib": ["esnext"],
"moduleResolution": "node",
"resolveJsonModule": true,
"inlineSourceMap": true,
"module": "esnext",
"esModuleInterop": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"strict": true,
"noImplicitAny": true,
"noEmit": true,
"types": [
"@cloudflare/workers-types",
"@types/bcryptjs"
]
},
"ts-node": {
"transpileOnly": true
},
"include": ["./src/**/*", "bindings.d.ts"]
}
Any idea what I am doing wrong?
Here is the code in question, modify from cloudflare durable objects example.
The version of Hono is 4.2.7, and wrangler is 3.52.0.
import { DurableObject } from 'cloudflare:workers';
import { Hono } from 'hono';
export type Bindings = {
COUNTERS: DurableObjectNamespace<Counter>;
}
const app = new Hono<{ Bindings: Bindings }>();
app.get('*', async (c) => {
const id = c.env.COUNTERS.idFromName('A');
const obj = c.env.COUNTERS.get(id);
// obj.getCounterValue should be an async function
console.log(obj.getCounterValue); // output: null
const value = await obj.getCounterValue();
return c.text(`Count is ${value}`);
});
export default app;
// Durable Object
export class Counter extends DurableObject {
async getCounterValue() {
const value = (await this.ctx.storage.get('value')) || 0;
return value;
}
async increment(amount = 1) {
let value: number = (await this.ctx.storage.get('value')) || 0;
value += amount;
await this.ctx.storage.put('value', value);
return value;
}
async decrement(amount = 1) {
let value: number = (await this.ctx.storage.get('value')) || 0;
value -= amount;
await this.ctx.storage.put('value', value);
return value;
}
}
obj.getCounterValue
should be an async function, but I got null
instead. vscode intellisense tells me obj.getCounterValue
has the type of never
, so I assume hono messed something up during the process.
Hi, getting this error in the browser when I try to run the page-stack example:
Also getting this error on http://127.0.0.1:8788/
I'm currently working on integrating Hono with Cloudflare Durable Objects following this example: Hono Example. However, I've run into a snag and need some help troubleshooting.
My implementation, which is essentially a replica of the original example, can be found here: My Hono Implementation.
When I run the worker and send requests to port 8787 (where the worker runs, I have confirmed) I see 404 not found for all routes '/', '/increment', '/decrement'. What could be the reason? In general how else can I test if the do works?
I'm trying to create a middleware which will convert post request body json from camel case to snake case, then response body json from snake case to camel case. The first part is OK, but I'm struggling with the second part. I raised it here, as I also thought it would be nice to add it to the examples. This is what I have so far:
import camelcaseKeys from 'camelcase-keys';
import snakecaseKeys from 'snakecase-keys';
function tryParseJSONObject (jsonString: string) {
try {
var o = JSON.parse(jsonString);
if (o && typeof o === "object") {
return o;
}
}
catch (e) { return e }
return undefined
}
app.use('*', async (c, next) => {
if (c.req.method === 'POST') {
let bodyText = await c.req.raw.clone().text()
let jsonObj = tryParseJSONObject(bodyText)
if (jsonObj && !(jsonObj instanceof Error)) {
c.json(snakecaseKeys(jsonObj))
}
}
await next()
try {
let body = await c.res.json()
if (body) {
// How do I set the response body json and avoid potential issues using cloning?
}
} catch(e) {}
})
pages-stack
is a really helpful example, but when I run it I get:
▲ [WARNING] Specifying a `-- <command>` or `--proxy` is deprecated and will be removed in a future version of Wrangler.
is there a more up to date example available?
It'd be great if there was an official example of how to use Taiwlind with Hono. It's a frequently asked topic on the Discord server.
For example, following the usual docs for getting Tailwind to work in dev on Cloudflare Pages works fine. However, I can't figure out how to get the CSS file to be created in a production build.
Hi, i'm just curious why do you export this fetch? Is it documented somewhere?
Line 40 in cbe7bf7
I can get the other examples works but when I run yarn dev
on the blog example, I get:
Running custom build: yarn run build
Usage Error: Couldn't find a script named "build".
$ yarn run [--inspect] [--inspect-brk] [-T,--top-level] [-B,--binaries-only] <scriptName> ...
✘ [ERROR] Command failed with exit code 1: yarn run build
I couldn't get an example of this combination working yet
Maybe this is too Cloudflare-specific for Hono, but it would be awesome to have something like itty-durable that makes integrating with Durable Objects type-safe and seamless, then Hono would truely be a full stack framework! (hono client + rpc + hono-do 😄 )
The static example works great.
import { Hono } from 'hono'
import { serveStatic } from 'hono/cloudflare-workers'
import manifest from '__STATIC_CONTENT_MANIFEST'
const app = new Hono()
app.get('/static/*', serveStatic({ root: './', manifest }))
app.use('/favicon.ico', serveStatic({ path: './favicon.ico', manifest }))
app.get('/', (c) => c.text('This is Home! You can access: /static/fallback.txt'))
Is there a way to get vitest
or jest
to stop complaining about __STATIC_CONTENT_MANIFEST
?
Error: Failed to load url __STATIC_CONTENT_MANIFEST (resolved id: __STATIC_CONTENT_MANIFEST) in foo.test.js. Does the file exist?
❯ loadAndTransform node_modules/vite/dist/node/chunks/dep-C-KAszbv.js:53848:21
From honojs/hono#606 the issue is still valid
Tested with:
/bun/tsconfig.json
from:
{
"compilerOptions": {
"jsx": "react-jsx",
"jsxFragmentFactory": "Fragment",
"jsxImportSource": "hono/jsx"
}
}
to:
{
"compilerOptions": {
"jsx": "preserve",
"jsxFragmentFactory": "Fragment",
"jsxImportSource": "hono/jsx"
}
}
Option 'jsxFragmentFactory' cannot be specified without specifying option 'jsxFactory'.
Which can be solved by adding "jsxFactory": "jsx",
Looking at https://github.com/honojs/examples/blob/main/durable-objects/src/counter.ts, I wanted to try something that makes a Durable Object feel more like a stateless application but with a c.state
property. So I came up with this:
const app = new HonoObject()
const getValue = async (storage: DurableObjectStorage) => await storage.get<number>('value') || 0
app.get('/increment', async (c) => {
const { storage } = c.state
const newVal = 1 + await getValue(storage);
storage.put('value', newVal)
return c.text(newVal.toString())
})
app.get('/decrement', async (c) => {
const { storage } = c.state
const newVal = -1 + await getValue(storage);
storage.put('value', newVal)
return c.text(newVal.toString())
})
app.get('/', async c => {
const value = await getValue(c.state.storage)
return c.text(value.toString())
})
export { app as Counter }
hello,
Thanks for the amazing hono.js.
would it be possible to update the examples to match v4 syntax?
I'm particularly having issues withserveStatic
, among other things.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.