kwhitley / itty-router

A little router.
MIT License
1.75k stars 78 forks source link

Middleware with parameters? #68

Closed socketopp closed 2 years ago

socketopp commented 2 years ago

Is it possible to write middleware that accepts parameters like my example below?

router.post('/ping', parseRequest('id123'), async (request, env) => {}

g45t345rt commented 2 years ago

Yes it is!

You can check how I use middleware here https://github.com/g45t345rt/cf-ssr-template/blob/9c4d9027fbe53e0cfbc2ce30899fd5b5f1e29538/src/server/post/index.ts#L9 https://github.com/g45t345rt/cf-ssr-template/blob/9c4d9027fbe53e0cfbc2ce30899fd5b5f1e29538/src/server/index.ts#L28

kwhitley commented 2 years ago

Thanks for answering @g45t345rt! And yeah @socketopp, definitely possible :)

Middleware is literally any function that either:

  1. responds with anything (breaks the response chain)... usually a Response unless you have something to catch the lack of Response downstream
  2. doesn't response (continues to handle other middleware/handlers until one does). This is how you would handle auth for instance... perhaps embedding the user into the request for future handlers, or conversely responding early with a 401 Response.

Hope this helps!