honojs / node-server Goto Github PK
View Code? Open in Web Editor NEWNode.js Server for Hono
Home Page: https://hono.dev
Node.js Server for Hono
Home Page: https://hono.dev
Hello! Thank you for this excellent tool - it's really helping solve a particular need.
Curious if there was a way to pipe process.env
into the "regular" context object? It's just always undefined currently.
Thank you!
Create vercel
and deprecate nextjs
.
serve static is not working, iam not using absolute path, minimal repro https://github.com/ibnumusyaffa/hono-serve-static-not-working
Thanks for a good work on open source.
I am using node-server
to run a very simple web page, but I encounter the error Error [ERR_STREAM_PREMATURE_CLOSE]: Premature close
quite often. After investigating alternative servers, I discovered that miniflare
is also aware of this issue and they don't use pipeline(..)
in their implementation. You can see their implementation at https://github.com/cloudflare/miniflare/blob/7e4d906e19cc69cd3446512bfeb7f8aee3a2bda7/packages/http-server/src/index.ts#L215-L241.
Although miniflare
works well, it is quite heavy. In order to have a stable and smooth runtime, I think we should follow miniflare
's approach in this implementation.
async function mainFetch(req: Request, _env: Record<string, string>): Promise<Response> {
const u = new URL(req.url);
if (u.pathname === '/favicon.ico') {
// seems like issue went here
return fetch('https://my-internal-site/favicon.ico');
}
return new Response('OK');
}
serve(
{
fetch(r) {
return mainFetch(r, {});
},
port: 3535,
},
(info) => console.log(`http://localhost:${info.port}`)
);
Run the complied code and access the webpage.
$ node dist/index.cjs
http://localhost:3535
Error [ERR_STREAM_PREMATURE_CLOSE]: Premature close
at new NodeError (node:internal/errors:399:5)
at ServerResponse.onclose (node:internal/streams/end-of-stream:154:30)
at ServerResponse.emit (node:events:525:35)
at emitCloseNT (node:_http_server:965:10)
at Socket.onServerResponseClose (node:_http_server:277:5)
at Socket.emit (node:events:525:35)
at TCP.<anonymous> (node:net:322:12) {
code: 'ERR_STREAM_PREMATURE_CLOSE'
}
CC: @yusukebe
We have to implement serveStatic
function like a Serve Static Middleware.
import { server, serveStatic } from '@honojs/node-server'
This project use remix-run/web-std-io as the underlying mechanism to support web standard.
While nodejs 18+ has already support that well, I think we should polyfill those implementations.
Pr will be made soon
Currently, serveStatic
does this:
$ node src/index.js
Static file: ./.reejs/__reejs/deps/render/index.js is not found
Static file: ./.reejs/__reejs/.reejs/deps/render/index.js is not found
Static file: ./.reejs/__reejs/deps/react/index.js is not found
Static file: ./.reejs/__reejs/cache/cache.json is not found
^C
______________________________________________________________________
$ cat src/index.js
import { serve } from '@hono/node-server';
import { Hono } from 'hono';
import {serveStatic} from '@hono/node-server/serve-static;
const app = new Hono();
app.get('/', (c) => c.text('Hello Hono!'));
app.use('/__reejs/**', serveStatic({root: './.reejs/'}));
serve(app)
My files are saved inside .reejs
folder, and not inside .reejs/__reejs
folder.
Suggested fix: add a new parameter called rewritePath
app.use(
'/__reejs/*',
serveStatic({ root: './.reejs/', rewritePath: (path: string) => path.replace(/^\/__reejs/, '') })
)
Express.js servers have close
method
How to destroy http server created by serve
function ?
serve({
fetch: honoServer.fetch,
port: 3001,
})
/Users/matteogauthier/dev/switch/node_modules/.pnpm/@[email protected]/node_modules/@honojs/node-server/dist/globals.js:23
global.crypto = node_crypto_1.default;
^
TypeError: Cannot set property crypto of #<Object> which has only a getter
at installGlobals (/Users/matteogauthier/dev/switch/node_modules/.pnpm/@[email protected]/node_modules/@honojs/node-server/dist/globals.js:23:12)
at <anonymous> (/Users/matteogauthier/dev/switch/node_modules/.pnpm/@[email protected]/node_modules/@honojs/node-server/dist/server.js:8:15)
at Object.<anonymous> (/Users/matteogauthier/dev/switch/node_modules/.pnpm/@[email protected]/node_modules/@honojs/node-server/dist/server.js:22:28)
at Module._compile (node:internal/modules/cjs/loader:1255:14)
at Object.F (/Users/matteogauthier/dev/switch/node_modules/.pnpm/@[email protected]/node_modules/@esbuild-kit/cjs-loader/dist/index.js:1:941)
at Module.load (node:internal/modules/cjs/loader:1113:32)
at Module._load (node:internal/modules/cjs/loader:960:12)
at Module.require (node:internal/modules/cjs/loader:1137:19)
at require (node:internal/modules/helpers:121:18)
at <anonymous> (/Users/matteogauthier/dev/switch/node_modules/.pnpm/@[email protected]/node_modules/@honojs/node-server/dist/index.js:4:16)
Node.js v20.2.0
my server
import { serve } from "@honojs/node-server"
import { Hono } from "hono"
const app = new Hono()
app.get("/", (c) => {
return c.text("Hello world!")
})
serve({
fetch: app.fetch,
port: 3111,
})
Hi, I'm getting the following error when trying to run a simple piece of code:
> NODE_ENV=production node dist/index.js
Starting server on port 8080
Listening on http://localhost:8080
/Users/rafael.almeida/github/rafaell/afw-api/node_modules/.pnpm/@[email protected]/node_modules/@hono/node-server/dist/listener.js:48
res = new Response(null, { status: 500 });
^
ReferenceError: Response is not defined
at Server.<anonymous> (/Users/rafael.almeida/github/rafaell/afw-api/node_modules/.pnpm/@[email protected]/node_modules/@hono/node-server/dist/listener.js:48:7)
at Server.emit (node:events:513:28)
at parserOnIncoming (node:_http_server:998:12)
at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)
ELIFECYCLE Command failed with exit code 1.
I'm compiling the code using tsup with the same setup I have for Express server.
TSUP Config:
import { defineConfig } from 'tsup'
export default defineConfig({
entryPoints: ['src/index.ts'],
platform: 'node',
target: 'es2020',
splitting: false,
sourcemap: true,
clean: true,
})
Code example:
import { serve } from '@hono/node-server'
import { Hono } from 'hono'
const app = new Hono()
app.get('/', (c) => c.text('Hono meets Node.js'))
serve({ fetch: app.fetch, port: 8080 }, (info) => {
console.log(`Starting server on port ${info.port}`)
console.log(`Listening on http://localhost:${info.port}`)
})
Dependencies:
"dependencies": {
"@hono/node-server": "1.2.0",
"hono": "3.7.3"
},
Here is the English translation for your request (except the code part):
Hi, I encountered a bug with the latest version of node-server 1.1.1 (no problems in 0.6.0)
Here is the bug:
3|api-supervision | /opt/nexview/backend/node_modules/.pnpm/@HONO[email protected]/node_modules/@hono/node-server/dist/listener.js:42
3|api-supervision | init.body = import_node_stream.Readable.toWeb(incoming);
3|api-supervision | ^
3|api-supervision | TypeError: import_node_stream.Readable.toWeb is not a function
3|api-supervision | at Server. (/opt/nexview/backend/node_modules/.pnpm/@HONO[email protected]/node_modules/@hono/node-server/dist/listener.js:42:47)
3|api-supervision | at Server.emit (node:events:513:28)
3|api-supervision | at Server.emit (node:domain:489:12)
3|api-supervision | at parserOnIncoming (node:_http_server:980:12)
3|api-supervision | at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)
Here are the files that create the bug (I shortened only the relevant code)
`import { Hono, Context } from "hono";
import { handleResponse } from "../helpers/utils";
import {
createRecorder,
createRecorderState,
} from "../controllers/supervisionController";
import { Recorder, RecorderState } from "../models/interfaces";
import { zValidator } from "@hono/zod-validator";
supervision.post(
"/v1/add-recorder",
//zValidator("json", AddRecorderValidator),
async (ctx: any) => {
//const body: AddRecorderInterface = await ctx.req.json();
console.log("body");
ctx.status(201);
return ctx.body("ok");
}
);
`
The server file:
`import { serve } from "@hono/node-server";
import { serveStatic } from "@hono/node-server/serve-static";
import { Context, Hono } from "hono";
import { logger } from "hono/logger";
import { cors } from "hono/cors";
import { checkTokenMiddleware } from "./middlewares/authMiddleware";
//Import des différents groupe de route
import { auth } from "./routes/authRoute";
import { user } from "./routes/userRoute";
import { network } from "./routes/networkRoute";
import { agency } from "./routes/agencyRoute";
import { supervision } from "./routes/supervisionRoute";
import { recorder } from "./routes/recorderRoute";
import { getCookie, setCookie, deleteCookie } from "hono/cookie";
const app = new Hono();
//Middlewares :
app.use("", logger());
app.use(
"",
cors({
origin: (origin) => origin,
credentials: true,
})
);
app.use("/static/", serveStatic());
//app.use("/static/", serveStatic({ root: "./" }));
app.route("/api/supervision/auth", auth);
app.route("/api/supervision", supervision); //this route
`
package json :
{ "scripts": { "start": "tsx src/server.ts" }, "prisma": { "seed": "ts-node prisma/seed.ts" }, "dependencies": { "@hono/node-server": "^1.1.1", "@hono/zod-validator": "^0.1.3", "@prisma/client": "^4.16.2", "bcrypt": "^5.1.0", "date-fns": "^2.30.0", "date-fns-tz": "^2.0.0", "hono": "^3.3.4", "jsonwebtoken": "^9.0.1", "sharp": "^0.32.3", "zod": "^3.21.4" }, "devDependencies": { "@types/bcrypt": "^5.0.0", "@types/jsonwebtoken": "^9.0.2", "@types/node": "^18.16.19", "prisma": "^4.16.2", "ts-node": "^10.9.1", "tsx": "^3.12.7", "typescript": "^5.1.6" } }
In my Deno applicaiton, I'm able to access the client's IP address on each request using some fairly convoluted, but nonetheless functional, means:
const app = new Hono();
app.get("/", (ctx) => {
return ctx.body(ctx.env.remoteAddr());
});
serve(async (request, connInfo) => {
const remoteAddr = () => resolveRemoteAddr(connInfo.remoteAddr);
const env = { remoteAddr };
return app.fetch(request, env);
}, {
hostname: "0.0.0.0",
port: 3001,
});
This does not appear possible in an equivalent node application, using honojs/node-server
. The function returned by getRequestListener
has access to the IncomingMessage
structure, which makes this available via message.socket.remoteAddress
, but that is not itself made available to the fetchCallback
, and the undici Request
object that is passed to the route doesn't appear to provide access to it either.
Am I missing something?
The Hono node server is throwing the following error:
Error [ERR_STREAM_PREMATURE_CLOSE]: Premature close
at new NodeError (node:internal/errors:405:5)
at ServerResponse.onclose (node:internal/streams/end-of-stream:154:30)
at ServerResponse.emit (node:events:526:35)
at emitCloseNT (node:_http_server:996:10)
at Socket.onServerResponseClose (node:_http_server:278:5)
at Socket.emit (node:events:526:35)
at TCP.<anonymous> (node:net:323:12) {
code: 'ERR_STREAM_PREMATURE_CLOSE'
}
This issue has been transferred from honojs/hono#1253.
Hi, I was wondering if it is possible to make the rawResponse accessible similar to c.req.raw ? Some API libraries require
nodes rawRequest and rawResponse to perform OAuth.
Hey! First of all thank you so much for your Hono and the Node.js adapter work - they are awesome!
I've noticed that this code works fine with just Hono on Vercel inside Next.js:
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { handle } from 'hono/vercel'
import * as z from 'zod'
const schema = z.object({
test: z.string(),
})
const app = new Hono().post('*', zValidator('query', schema), (c) =>
c.text('test')
)
export default handle(app)
export const runtime = 'edge'
But when using the honojs/node-server
like so:
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { handle } from '@hono/node-server/vercel'
import * as z from 'zod'
const schema = z.object({
test: z.string(),
})
const app = new Hono().post('*', zValidator('query', schema), (c) =>
c.text('test')
)
export default handle(app)
I am getting:
TypeError: Response body object should not be disturbed or locked
at extractBody (node:internal/deps/undici/undici:5178:17)
at new Request (node:internal/deps/undici/undici:6160:48)
at newRequestFromIncoming (file:///hono-tests/node_modules/@hono/node-server/dist/vercel.mjs:160:10)
at [getRequestCache] (file:///hono-tests/node_modules/@hono/node-server/dist/vercel.mjs:173:35)
at Request.get (file:///hono-tests/node_modules/@hono/node-server/dist/vercel.mjs:192:35)
at HonoRequest.header (file:///hono-tests/node_modules/hono/dist/request.js:73:23)
at /hono-tests/node_modules/hono/dist/cjs/validator/validator.js:29:31
at dispatch (file:///hono-tests/node_modules/hono/dist/compose.js:29:23)
at file:///hono-tests/node_modules/hono/dist/compose.js:6:12
at file:///hono-tests/node_modules/hono/dist/hono-base.js:247:31
at Hono.dispatch (file:///hono-tests/node_modules/hono/dist/hono-base.js:257:7)
at fetch (file:///hono-tests/node_modules/hono/dist/hono-base.js:59:19)
at file:///hono-tests/node_modules/@hono/node-server/dist/vercel.mjs:275:13
at /hono-tests/node_modules/next/dist/compiled/next-server/pages-api.runtime.dev.js:21:3039
at /hono-tests/node_modules/next/dist/server/lib/trace/tracer.js:133:36
Without zValidator
it also works as expected.
In #115, an explicit instanceof Response
check was added. This breaks for libraries/integrations that use the @whatwg-node/events ponyfill package. A prominent example is graphql-yoga which can no longer be used with hono & node-server because the response returned is an instance of PonyfillResponse that does not pass the instanceof Response
check.
Reverting to 1.3.3 resolves the problem.
Indeed, the Hono app, when using node-server, is slow. You can see the benchmarks here:
https://github.com/SaltyAom/bun-http-framework-benchmark
However, there are opportunities to improve performance, and we should do them.
Whenever we include a payload to a request using @hono/node-server/vercel
, Hono silently fails and just returns a 500
response.
Here's a minimal repro:
https://github.com/alexiglesias93/hono-vercel-bug/blob/master/api/index.ts
Deployed:
https://hono-vercel-bug.vercel.app/api
NodeJS version in Vercel: 18.x
NodeJS version in local: 18.16.1
Error happens in both Vercel and local (using vercel dev
).
I've been able to pinpoint the issue to these lines in listener.ts
, after adding a console log in the catch
statement I was able to find out that Vercel is failing with this error:
TypeError: Response body object should not be disturbed or locked
at extractBody (node:internal/deps/undici/undici:6342:17)
at new Request (node:internal/deps/undici/undici:7216:48)
at file:///C:/Development/hono-vercel-bug/node_modules/.pnpm/@HONO[email protected]/node_modules/@hono/node-server/dist/listener.mjs:26:33
at Server. (file:///C:/Development/hono-vercel-bug/node_modules/.pnpm/@vercel[email protected]/node_modules/@vercel/node/dist/serverless-functions/serverless-handler.mjs:14:16)
at processTicksAndRejections (node:internal/process/task_queues:95:5)
I also tried to update vercel
from 29.4.0
to 32.2.5
but still getting a similar error.
Update: seems that this line in particular is the one causing the error. If I comment it out, the request goes through without errors.
Any thoughts? This is quite a blocker to implement Hono in Vercel
Let me know if I can do anything to help!
Currently, we use getSetCookie
from Headers
to parse set-cookie
header values.
Line 55 in 003e6dd
This works well on all our CI environments: Node 18.x, 19.x, and 20.x.
However, getSetCookie
is not fully supported before version 19.7.
https://developer.mozilla.org/en-US/docs/Web/API/Headers/getSetCookie
Thus, it will throw an error in "18.0.0", even though the latest "18.x" does support getSetCookie
.
We have stated that this Node.js adapter works on Node.js "18". Therefore, I believe we need to implement a cookie parsing function instead of using the native getSetCookie()
.
The implementation could be simple, something along the lines of:
export const getSetCookieFromString = (str: string): string[] => {
return str.split(/\s*\,\s*/)
}
The following a "proxy pattern" is not working:
import { serve } from '@hono/node-server'
import { Hono } from 'hono'
const app = new Hono()
app.get('/proxy', async (c) => {
const res = await fetch('https://example.com/')
const newResponse = new Response(res.body, res)
return newResponse
})
serve({
fetch: app.fetch,
port: 3000
})
Commented honojs/hono#1491 (comment)
We have to add a linter to this project.
just keep it normal, like dont serve index.html unless explicitly set to...
app.use('/__reejs/**', serveStatic({ root: './.reejs/', rewriteRequestPath:(p)=>p.replace('__reejs','') }));
app.use('/', serveStatic({ file: "./.reejs/serve/index.html" }));
app.use('/**', serveStatic({ root: './public/' }));
as of @hono/[email protected]
, this code still doesnt work properly ...
This above code doesnt seve files inside .reejs
folder properly, serves index.html
when didnt ask to, and neither file
option seems to work for me.
While it sounds reasonable to have served index.html automatically, I would suggest making that opt-in.
Like:
app.use('/', serveStatic({ staticWebsite: true });
would just do the job.
Currently, the docs for Vercel only explain how to deploy Hono on the edge runtime.
When removing the runtime: 'edge'
config, Hono doesn't work anymore.
After some digging, I found this PR in the node-server adapter that seems to implement exactly what I need, but with the lack of documentation I haven't been able to successfully use the adapter. I might be doing something wrong but can't find the issue.
Any help/documentation will be appreciated, thank you very much for the work you're doing.
This is my setup:
import { Hono } from 'hono';
import { handle } from '@hono/node-server/vercel';
const app = new Hono().basePath('/api');
app.get('/', (c) => c.json({ message: 'Hello Hono!' }));
export default handle(app);
And the following TypeError is thrown when running the app and visiting the http://localhost:3000/api
route:
Argument of type 'Hono<Env, {}, "/api">' is not assignable to parameter of type 'Hono<Env, {}, "" | "/api">'.
The types of 'route(...).all(...).route(...).use' are incompatible between these types.
Type 'MiddlewareHandlerInterface<Env, RemoveBlankRecord<RemoveBlankRecord<Record<string, unknown> | Schema<"all", string, any, any>>>, "/api">' is not assignable to type 'MiddlewareHandlerInterface<Env, RemoveBlankRecord<RemoveBlankRecord<Record<string, unknown> | Schema<"all", string, any, any>>>, "" | "/api">'.
Types of parameters 'handlers' and 'handlers' are incompatible.
Types of parameters 'c' and 'c' are incompatible.
Type 'Context<Env, `/api/${string}`, {}>' is not assignable to type 'Context<Env, string, {}>'.
Types of property 'req' are incompatible.
Type 'HonoRequest<`/api/${string}`, unknown>' is not assignable to type 'HonoRequest<string, unknown>'.
Type 'string' is not assignable to type '`/api/${string}`'.
Adding @ts-expect-error
solves the issue:
// @ts-expect-error
export default handle(app);
This is my setup:
import { Hono } from 'hono';
import { handle } from '@hono/node-server/vercel';
const app = new Hono().basePath('/api');
app.get('/', (c) => c.json({ message: 'Hello Hono!' }));
// @ts-expect-error
export default handle(app);
After silencing the #49 error using @ts-expect-error
, I get a new error when visiting http://localhost:3000/api
:
file:///C:/Development/honojs-testing/node_modules/.pnpm/@[email protected]/node_modules/@vercel/node/dist/serverless-functions/serverless-handler.mjs:14
return userCode(req, res);
^
ReferenceError: Response is not defined
at C:\Development\honojs-testing\node_modules\.pnpm\@[email protected]\node_modules\@hono\node-server\dist\listener.js:30:13
at Server.<anonymous> (file:///C:/Development/honojs-testing/node_modules/.pnpm/@[email protected]/node_modules/@vercel/node/dist/serverless-functions/serverless-handler.mjs:14:16)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
The NodeJS version is set to 18.x
in Vercel.
I can provide a GitHub repository if further context is needed!
the compress()
middleware on node is very slow. I tested the minified version of htmx (44KB) and it takes more than 2000ms until i get a html response from the server. I use node version v20.5.1
Can someone explain how it works that no build step is needed to use JSX in node? In other frameworks build step is needed to turn JSX into js.
Hello! I am following the guidance here to setup up Hono with Node / Vercel adapter https://hono.dev/getting-started/vercel#node-js
I scaffolded the project with create hono
to give a package.json like this:
{
"name": "myapp",
"module": "src/index.ts",
"type": "module",
"scripts": {
"vercel-dev": "vercel dev",
"deploy": "vercel"
},
"dependencies": {
"hono": "^3.7.2",
},
"devDependencies": {
"vercel": "^32.4.1"
}
}
When running the dev script "vercel dev", it errors asking for a "build" script as well. Do you have any ideas for what to put there? thanks so much!
Vercel CLI 32.4.1
Error: Your `package.json` file is missing a `build` property inside the `scripts` property.
Learn More: https://vercel.link/missing-build-script
Since updating to @hono/[email protected], I'm having an issue using GraphQL Yoga. The server immediately crashes with the below message:
TypeError: The "readableStream" argument must be an instance of ReadableStream. Received an instance of bound PonyfillReadableStream
at new NodeError (node:internal/errors:399:5)
at Object.newStreamReadableFromReadableStream (node:internal/webstreams/adapters:482:11)
at Function.Readable.fromWeb (node:internal/streams/readable:1403:27)
at Server.<anonymous> (file:///workspace/node_modules/@hono/node-server/dist/listener.mjs:49:35)
at processTicksAndRejections (node:internal/process/task_queues:95:5) {
code: 'ERR_INVALID_ARG_TYPE'
I have created a minimal reproduction on https://codesandbox.io/p/sandbox/optimistic-lichterman-tvsgh8
Rolling back to @hono/[email protected] fixes the issue.
Because the server use res.text() instead of streaming when content-type starts with 'text', so 'text/event-strream' is also fully buffered.
Using @hono/node-server
with hono/compress
middleware does not work.
The server crashes
Minimal example:
import { serve } from '@hono/node-server'
import { Hono } from 'hono'
import { compress } from 'hono/compress'
const app = new Hono()
app.use('*', compress())
app.get('/one', async (c) => {
let body = 'one'
for (let index = 0; index < 1000 * 1000; index++) {
body += ' one'
}
return c.text(body)
})
const _server = serve({
fetch: app.fetch,
port: 8081,
})
Error output
Trace: TypeError: First parameter has member 'readable' that is not a ReadableStream.
at assertReadableStream (/Users/example/example/core/node_modules/web-streams-polyfill/src/lib/validators/readable-stream.ts:5:11)
at convertReadableWritablePair (/Users/example/example/core/node_modules/web-streams-polyfill/src/lib/validators/readable-writable-pair.ts:15:3)
at ReadableStream.pipeThrough (/Users/example/example/core/node_modules/web-streams-polyfill/src/lib/readable-stream.ts:211:23)
at /Users/example/example/core/lab/node_modules/hono/dist/cjs/middleware/compress/index.js:35:41
at processTicksAndRejections (node:internal/process/task_queues:95:5)
at async /Users/example/example/core/lab/node_modules/hono/dist/cjs/hono.js:227:50
at async Server.<anonymous> (/Users/example/example/core/node_modules/@hono/node-server/dist/listener.js:29:20)
at errorHandler (/Users/example/example/core/lab/node_modules/hono/dist/cjs/hono.js:43:11)
at /Users/example/example/core/lab/node_modules/hono/dist/cjs/compose.js:80:27
at processTicksAndRejections (node:internal/process/task_queues:95:5)
at async /Users/example/example/core/lab/node_modules/hono/dist/cjs/hono.js:227:50
at async Server.<anonymous> (/Users/example/example/core/node_modules/@hono/node-server/dist/listener.js:29:20)
Hi, How do you compare performance with other node.js frameworks?
Which tool or command do you use for benchmarking?
I did something like https://github.com/OnurGvnc/hono-node-server/tree/dev/benchmarks
{ connections: 50, duration: 10 }
fastify 105,594 req/seq
hono 50,012 req/seq
express 24,613 req/seq
hono (undici) 17,648 req/seq
with MacBookAir10,1 M1 16GB RAM 8 Core
In my testing the compress middleware made a serveStatic
HTML page return plain text text/plain;charset=UTF-8
.
https://hono.dev/middleware/builtin/compress
Hey I was expecting the result of the "file" input's result to be an instance of "File" instead of a string, is this normal behavior? Here's an example of it returning a string.
Regards,
Luis Bizarro.
Hi! I got following error when I tried to set cookie:
TypeError: res.headers.getSetCookie is not a function
It comes from @hono/node-server/dist/listener.js:47
:
outgoing.setHeader(k, res.headers.getSetCookie(k));
Tested on node v18.6.0 and v20.3.0
Code:
import { Hono } from 'hono';
import { serve } from '@hono/node-server';
import { setCookie } from 'hono/cookie';
const app = new Hono();
app.get('/', c => {
setCookie(c, 'token', '123');
return c.text('Cookie set');
});
serve({ fetch: app.fetch, port: 3001 });
Hey!
I'm trying to add SSL to our dev env but can't seem to access this line in an elegant way.
I assume that by swapping that out with the createServer
from node:https
would do the trick.
Line 12 in 68b2475
A solution could be either default to node:https
or expose getRequestListener
so that we can create our own serve
with https.
What do you think?
With Node.js v20.3.0, post to localhost:3000
by axios succeeds, but with v18.16.0, I get an error Error: connect ECONNREFUSED ::1:3000
and cannot post successfully.
I did not get any errors from hono.
However, post requests made via testers such as Advanced REST Client seem to succeed.
Node.js v20.3.0 で axios を使って localhost:3000
へ post すると成功しますが、v18.16.0 の場合は Error: connect ECONNREFUSED ::1:3000
というエラーが発生し、正常に post することができません。
hono からはエラーは出ていませんでした。
なお、Advanced REST Client のようなテスター経由の post リクエストは成功するようです。
NodeJS now supports fetch natively, but the fetch api that's replacing the native fetch is causing some issues.
It doesnt allow me to load relative/local file where the native fetch allows you to.
c.req.raw.signal does not work even when the client is disconnected.
It seems that there is no event handling for http.ClientRequest.
I want to mount a Hono router on an Express router like this:
const app = express();
const hono = new Hono();
app.use("/hoge", getRequestListener(hono.fetch));
To achieve this, I'd like you to export the getRequestListener.
Using @hono/node-server
, all of my response bodies are being gobbled up.
This happens whether I'm generating a response or serving static files. All middleware is disabled.
The correct status codes and headers are being applied. (The one exception is 'Content-Length': 0, but that happens after any code I have access to.)
If I call app.request()
, I receive the correct response. If I use hono/bun
, it also works.
I'm on node 18.16.1. Any idea what's causing this?
Hi, I've created a discussion but it's worth adding it here as well.
Essentially Node.js has its own HTTP events such as close
| error
| finish
| timeout
that can be used with middleware like morgan to log/collect data and more.
To add more context, we use it to collect metrics such as response time, request ID (UUID generated by another middleware), and other things.
I've got @hono
org/namespace on the npm registry!
Let's move it to @hono/node-server
!
Right now the original IncomingMessage
from node is being added to Request#symbol(incomingKey)
but since it's using the symbol it is not possible to access afterwards.
I'm trying to see if it would be possible to use Hono in our applications at work and this would make it a lot easier as it allow us to write a wrapper around middleware for other frameworks or native node handlers.
i.e. c.req.raw.incomingMessage
, c.res.raw
or something similar
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.