feat(middleware): introduce Request ID middleware (#3082)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat(middleware): introduce Request ID middleware * fix not to accept empty string in header * rename requestID to requestId * pass the context to the generator option * add typesVersions * fix typo Co-Authored-By: Taku Amano <taku@taaas.jp> * change to generate id if validation fails Co-Authored-By: Taku Amano <taku@taaas.jp> * fix limit length test ---------
authored by ryu · committed by GitHub · parent c2698fa · Browse files · 5 files·+231 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Taku Amano <taku@taaas.jp>
Diff stats
5 files+231 added−0 removed
- tests:+155 added−0 removed
- other:+76 added−0 removed
Provenance
- Commit
e6d253d- Tree
ede8c82- Author
ryu <114303361+ryuapp@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
c2698fa
5 files changed+231 added−0 removed
added:src/middleware/request-id/index.test.ts+155 added
1+import type { Context } from '../../context'2+import { Hono } from '../../hono'3+import { requestId } from '.'4+5+const regexUUIDv4 = /([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})/6+7+describe('Request ID Middleware', () => {8+ const app = new Hono()9+ app.use('*', requestId())10+ app.get('/requestId', (c) => c.text(c.get('requestId') ?? 'No Request ID'))11+12+ it('Should return random request id', async () => {13+ const res = await app.request('http://localhost/requestId')14+ expect(res).not.toBeNull()15+ expect(res.status).toBe(200)16+ expect(res.headers.get('X-Request-Id')).toMatch(regexUUIDv4)17+ expect(await res.text()).match(regexUUIDv4)18+ })19+20+ it('Should return custom request id', async () => {21+ const res = await app.request('http://localhost/requestId', {22+ headers: {23+ 'X-Request-Id': 'hono-is-cool',24+ },25+ })26+ expect(res).not.toBeNull()27+ expect(res.status).toBe(200)28+ expect(res.headers.get('X-Request-Id')).toBe('hono-is-cool')29+ expect(await res.text()).toBe('hono-is-cool')30+ })31+32+ it('Should return random request id without using request header', async () => {33+ const res = await app.request('http://localhost/requestId', {34+ headers: {35+ 'X-Request-Id': 'Hello!12345-@*^',36+ },37+ })38+ expect(res).not.toBeNull()39+ expect(res.status).toBe(200)40+ expect(res.headers.get('X-Request-Id')).toMatch(regexUUIDv4)41+ expect(await res.text()).toMatch(regexUUIDv4)42+ })43+})44+45+describe('Request ID Middleware with custom generator', () => {46+ function generateWord() {47+ return 'HonoIsWebFramework'48+ }49+ function generateDoubleRequestId(c: Context) {50+ const honoId = c.req.header('Hono-Request-Id')51+ const ohnoId = c.req.header('Ohno-Request-Id')52+ if (honoId && ohnoId) {53+ return honoId + ohnoId54+ }55+ return crypto.randomUUID()56+ }57+ const app = new Hono()58+ app.use('/word', requestId({ generator: generateWord }))59+ app.use('/doubleRequestId', requestId({ generator: generateDoubleRequestId }))60+ app.get('/word', (c) => c.text(c.get('requestId') ?? 'No Request ID'))61+ app.get('/doubleRequestId', (c) => c.text(c.get('requestId') ?? 'No Request ID'))62+ it('Should return custom request id', async () => {63+ const res = await app.request('http://localhost/word')64+ expect(res).not.toBeNull()65+ expect(res.status).toBe(200)66+ expect(res.headers.get('X-Request-Id')).toBe('HonoIsWebFramework')67+ expect(await res.text()).toBe('HonoIsWebFramework')68+ })69+70+ it('Should return complex request id', async () => {71+ const res = await app.request('http://localhost/doubleRequestId', {72+ headers: {73+ 'Hono-Request-Id': 'Hello',74+ 'Ohno-Request-Id': 'World',75+ },76+ })77+ expect(res).not.toBeNull()78+ expect(res.status).toBe(200)79+ expect(res.headers.get('X-Request-Id')).toBe('HelloWorld')80+ expect(await res.text()).toBe('HelloWorld')81+ })82+})83+84+describe('Request ID Middleware with limit length', () => {85+ const charactersOf255 = 'h'.repeat(255)86+ const charactersOf256 = 'h'.repeat(256)87+88+ const app = new Hono()89+ app.use('/requestId', requestId())90+ app.use('/limit256', requestId({ limitLength: 256 }))91+ app.get('/requestId', (c) => c.text(c.get('requestId') ?? 'No Request ID'))92+ app.get('/limit256', (c) => c.text(c.get('requestId') ?? 'No Request ID'))93+94+ it('Should return custom request id', async () => {95+ const res = await app.request('http://localhost/requestId', {96+ headers: {97+ 'X-Request-Id': charactersOf255,98+ },99+ })100+ expect(res).not.toBeNull()101+ expect(res.status).toBe(200)102+ expect(res.headers.get('X-Request-Id')).toBe(charactersOf255)103+ expect(await res.text()).toBe(charactersOf255)104+ })105+ it('Should return random request id without using request header', async () => {106+ const res = await app.request('http://localhost/requestId', {107+ headers: {108+ 'X-Request-Id': charactersOf256,109+ },110+ })111+ expect(res).not.toBeNull()112+ expect(res.status).toBe(200)113+ expect(res.headers.get('X-Request-Id')).toMatch(regexUUIDv4)114+ expect(await res.text()).toMatch(regexUUIDv4)115+ })116+ it('Should return custom request id with 256 characters', async () => {117+ const res = await app.request('http://localhost/limit256', {118+ headers: {119+ 'X-Request-Id': charactersOf256,120+ },121+ })122+ expect(res).not.toBeNull()123+ expect(res.status).toBe(200)124+ expect(res.headers.get('X-Request-Id')).toBe(charactersOf256)125+ expect(await res.text()).toBe(charactersOf256)126+ })127+})128+129+describe('Request ID Middleware with custom header', () => {130+ const app = new Hono()131+ app.use('/requestId', requestId({ headerName: 'Hono-Request-Id' }))132+ app.get('/emptyId', requestId({ headerName: '' }))133+ app.get('/requestId', (c) => c.text(c.get('requestId') ?? 'No Request ID'))134+ app.get('/emptyId', (c) => c.text(c.get('requestId') ?? 'No Request ID'))135+136+ it('Should return custom request id', async () => {137+ const res = await app.request('http://localhost/requestId', {138+ headers: {139+ 'Hono-Request-Id': 'hono-is-cool',140+ },141+ })142+ expect(res).not.toBeNull()143+ expect(res.status).toBe(200)144+ expect(res.headers.get('Hono-Request-Id')).toBe('hono-is-cool')145+ expect(await res.text()).toBe('hono-is-cool')146+ })147+148+ it('Should not return request id', async () => {149+ const res = await app.request('http://localhost/emptyId')150+ expect(res).not.toBeNull()151+ expect(res.status).toBe(200)152+ expect(res.headers.get('X-Request-Id')).toBeNull()153+ expect(await res.text()).toMatch(regexUUIDv4)154+ })155+})added:src/middleware/request-id/index.ts+8 added
12345678import type { RequestIdVariables } from './request-id'export type { RequestIdVariables }export { requestId } from './request-id'import type {} from '../..'
declare module '../..' { interface ContextVariableMap extends RequestIdVariables {}}added:src/middleware/request-id/request-id.ts+59 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859/** * @module * Request ID Middleware for Hono. */
import type { Context } from '../../context'import type { MiddlewareHandler } from '../../types'
export type RequestIdVariables = { requestId: string}
export type RequestIdOptions = { limitLength?: number headerName?: string generator?: (c: Context) => string}
/** * Request ID Middleware for Hono. * * @param {object} options - Options for Request ID middleware. * @param {number} [options.limitLength=255] - The maximum length of request id. * @param {string} [options.headerName=X-Request-Id] - The header name used in request id. * @param {generator} [options.generator=() => crypto.randomUUID()] - The request id generation function. * * @returns {MiddlewareHandler} The middleware handler function. * * @example * ```ts * type Variables = RequestIdVariables * const app = new Hono<{Variables: Variables}>() * * app.use(requestId()) * app.get('/', (c) => { * console.log(c.get('requestId')) // Debug * return c.text('Hello World!') * }) * ``` */export const requestId = ({ limitLength = 255, headerName = 'X-Request-Id', generator = () => crypto.randomUUID(),}: RequestIdOptions = {}): MiddlewareHandler => { return async function requestId(c, next) { // If `headerName` is empty string, req.header will return the object let reqId = headerName ? c.req.header(headerName) : undefined if (!reqId || reqId.length > limitLength || /[^\w\-]/.test(reqId)) { reqId = generator(c) }
c.set('requestId', reqId) if (headerName) { c.header(headerName, reqId) } await next() }}modified:jsr.json+1 added
47 unmodified lines48495051525354555661 unmodified lines47 unmodified lines "./logger": "./src/middleware/logger/index.ts", "./method-override": "./src/middleware/method-override/index.ts", "./powered-by": "./src/middleware/powered-by/index.ts", "./pretty-json": "./src/middleware/pretty-json/index.ts", "./request-id": "./src/middleware/request-id/request-id.ts", "./secure-headers": "./src/middleware/secure-headers/secure-headers.ts", "./ssg": "./src/helper/ssg/index.ts", "./streaming": "./src/helper/streaming/index.ts", "./validator": "./src/validator/index.ts",61 unmodified linesmodified:package.json+8 added
221 unmodified lines222 "types": "./dist/types/middleware/pretty-json/index.d.ts",223 "import": "./dist/middleware/pretty-json/index.js",224 "require": "./dist/cjs/middleware/pretty-json/index.js"225 },226+ "./request-id": {227+ "types": "./dist/types/middleware/request-id/index.d.ts",228+ "import": "./dist/middleware/request-id/index.js",229+ "require": "./dist/cjs/middleware/request-id/index.js"230+ },231 "./secure-headers": {232 "types": "./dist/types/middleware/secure-headers/index.d.ts",233 "import": "./dist/middleware/secure-headers/index.js",234 "require": "./dist/cjs/middleware/secure-headers/index.js"245 unmodified lines480 ],481 "pretty-json": [482 "./dist/types/middleware/pretty-json"483 ],484+ "request-id": [485+ "./dist/types/middleware/request-id"486+ ],487 "streaming": [488 "./dist/types/helper/streaming"489 ],490 "ssg": [144 unmodified lines