Coder Social home page Coder Social logo

node-server's People

Contributors

alexfriesen avatar ariskemper avatar beeequeue avatar collinstevens avatar doge1338 avatar ezg27 avatar ff2400t avatar hagishi avatar hoodgail avatar ibodev1 avatar jarqvi avatar m4rc3l05 avatar marbemac avatar marvin-j97 avatar mindplay-dk avatar onurgvnc avatar renhiyama avatar ryuapp avatar tangye1234 avatar tavvy avatar that-ambuj avatar tsctx avatar usualoma avatar wenerme avatar yovach avatar yusukebe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

node-server's Issues

How to use environment vars from context?

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!

Error [ERR_STREAM_PREMATURE_CLOSE]: Premature close in Node Pipeline stream

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.


My code

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

serveStatic need optional parameter that allows to edit the route to file path

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/, '') })
)

How to destroy/close server ?

Express.js servers have close method

How to destroy http server created by serve function ?

serve({
        fetch: honoServer.fetch,
        port: 3001,
      })

`Cannot set property crypto of #<Object> which has only a getter` with Hono 3.2.4 and Node 20.2.0

/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,
})

ReferenceError: Response is not defined

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"
  },

TypeError: import_node_stream.Readable.toWeb is not a function

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" } }

Unable to access remoteAddr in route using node

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?

`ERR_STREAM_PREMATURE_CLOSE` error

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.

Unable to use zValidator for query with POST requests

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.

`500` responses when including `body` payload in any request using `@hono/node-server/vercel`

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!

`getSetCookie` is not fully supported before version 19.7

Currently, we use getSetCookie from Headers to parse set-cookie header values.

outgoing.setHeader(k, (res.headers as any).getSetCookie(k))

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*/)
}

Proxy is not working

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)

Add linter

We have to add a linter to this project.

Work on serve-static properly

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.

Document how to use Hono with Vercel & NodeJS runtime

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.

TypeError when using `@hono/node-server/vercel`

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);

Response is not defined in `@hono/node-server/vercel`

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!

compress middleware is slow

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

Build step

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.

Vercel build script

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

ReadableStream issue @hono/node-server <> GraphQL Yoga

Issue

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'

Reproduction

I have created a minimal reproduction on https://codesandbox.io/p/sandbox/optimistic-lichterman-tvsgh8

Workaround

Rolling back to @hono/[email protected] fixes the issue.

Not support SSE

Because the server use res.text() instead of streaming when content-type starts with 'text', so 'text/event-strream' is also fully buffered.

Server crashes when using compress middleware

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)

benchmark

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

TypeError: `res.headers.getSetCookie` is not a function

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 });

SSL support

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.

const server: Server = createServer(options.serverOptions || {}, requestListener)

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?

Handle an invalid response

It should handle an invalid response that is not an instance of Response:

app.get('/invalid', () => {
  return '<h1>Hello!</h1>'
})

serve({
  fetch: app.fetch,
  port: 3000
})

Currently, the application does not throw the correct error:

Screenshot 2023-12-27 at 22 03 57

Unable to post from axios on certain Node.js versions

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 リクエストは成功するようです。

Fetch API

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.

Abort is not working.

c.req.raw.signal does not work even when the client is disconnected.
It seems that there is no event handling for http.ClientRequest.

Export getRequestListener to use with express

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.

Empty response body for all requests

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?

`@honojs` to `@hono`

I've got @hono org/namespace on the npm registry!

Let's move it to @hono/node-server!

Make Original `IncomingMessage` and `ServerResponse` Publicly Accessible

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.