Comments (6)
Hi @rafaell-lycan,
To handle Node.js specific matters, I'm considering passing IncomingMessage
as part of the Bindings in @hono/node-server
. This way, you can access it with c.env.IncomingMessage
:
import { Hono } from 'hono'
import { serve } from '@hono/node-server'
import { IncomingMessage } from 'http'
type Bindings = {
IncomingMessage: IncomingMessage
}
const app = new Hono<{ Bindings: Bindings }>()
app.get('/', (c) => {
return c.text(`You access from ${c.env.IncomingMessage.socket.remoteAddress}`)
})
serve(app)
With access to IncomingMessage
, I think you can create a logger similar to morgan.
from node-server.
I think you can do it. I think you can declare that middleware on top of the handlers/middleware.
The following Logger middleware implementation would be helpful:
https://github.com/honojs/hono/blob/main/src/middleware/logger/index.ts
from node-server.
@yusukebe I'm not sure if this would work on this scenario.
Consider it as a middleware that acts after the route resolution.
(request) -> [middleware] -> (route match) -> [handler] -> (event)
How this implementation would look like? I was digging a bit on this pkg implementation but I haven't found where we could potentially create a mediator/event-dispatcher for it (probably on Hono's core).
I believe this could be a simple feature that can be enabled/disabled at the config level.
import { Hono, MiddlewareHandler } from 'hono'
import { serve } from '@hono/node-server'
// It could be always enabled when used with `@hono/node-server`
// and optional (different implementation) for Edge.
const app = new Hono({ enableEvents: true })
const eventLoggerMiddleware = (): MiddlewareHandler => async (ctx, next) => {
// Available with Context
ctx.on('finish', () => {
// Magic goes here.
})
await next()
}
// OR with custom events `onEvent` with Hono
app.onFinished((ctx) => {
// Magic goes here.
})
app.use('*', eventLoggerMiddleware())
app.get('/', (ctx) => {
return ctx.text('My shining new API')
})
serve(app)
from node-server.
@yusukebe any ideas if this will be supported or any workaround to make it work?
from node-server.
I'm not super familiar with Node.js. The mental model of Node.js is different from the Web Standard API used by Cloudflare Workers and others. These runtimes don't use the timing like a finish
. So, I might not yet fully understand it.
I think you already know it, but f it is only to be executed at the very end, you can write this:
const app = new Hono()
app.use(async (c, next) => {
await next()
// logging
})
app.get('/', (c) => c.json('handler'))
Or, with PR #129, you can now take the IncomingMessage
from c.env
and use that.
from node-server.
@yusukebe what I'm trying to accomplish is essentially migrate a few middleware (Express) which calculates the total time of the request and send the data to my metrics collector (OTL/Datadog) later.
Implementation-wise you imagine the following scenario:
- You add a middleware which will collect all the data you need;
- On every request, the middleware sets defines a
requestId
andstartAt
used later to calculate how long the full request took to complete including the requeststatus
(SLA/SLO control),path
,user-agent
and a few other bits
Would this be possible?
app.use(async (c, next) => {
const startTime = performance.now()
const requestId = c.req.header('x-request-id') ?? uuid()
await next()
const tags = {
...getContextTags(), // additional tags from an AsyncLocalStorage
request_id: requestId,
path: c.req.routePath,
"user-agent": c.req.header('User-Agent'),
method: c.req.method,
// HTTP Code - No idea how to retrieve this | Express: res.statusCode.toString()
response_code: c.res.status // ?,
}
const duration = Math.floor(performance.now() - startTime)
collector.timing('http.request_latency', duration, tags)
})
app.get('/', (c) => c.json('handler'))
from node-server.
Related Issues (20)
- Support compression gzip and deflate
- Vercel node issue: Cannot find module HOT 1
- Unified access to environment variables? HOT 3
- should use `writeFromReadableStream()` for a `ReadableStream` HOT 1
- `c.req.url` is always http HOT 7
- `app.mount()` is not working with `@hono/node-server` HOT 2
- TypeError: Cannot read private member #body from an object whose class did not declare it HOT 5
- SSE events not being output to clients HOT 1
- How to deal with `ERR_HTTP_HEADERS_SENT` errors? HOT 1
- Optimisations breaking `instanceof Response` checks HOT 6
- TypeError: Class extends value undefined is not a constructor or null HOT 3
- Denial of Service in newRequest HOT 10
- Determine behaviour for HTTP1.0 request w/o Host header
- Return 400 or 500 if the Host header contains a path. HOT 1
- GET request -> c.req.body returns ReadableStream HOT 1
- HTTP TRACE method crashes server
- docker run get Cannot find package '@/models' imported from error HOT 2
- Issue with RequestError having static name property HOT 1
- Memory leak with `hono`, `@hono/node-server`, `@hono/graphql-server`
- Bug: Unable to use Hono in Nextjs 14 App Dir with nodejs runtime HOT 5
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from node-server.