Next.js Discord

Discord Forum

Run code for every route (without middleware)

Unanswered
Oak saucer gall posted this in #help-forum
Open in Discord
Oak saucer gallOP
Hello, I'm looking for something similar to node's "app.use()", as I'd like to run a bit of code (mostly for rate limiting) for every api or route hit in the nextjs application. Is there a simple way to do this?

21 Replies

Dutch
middleware 😄, sad but true
cuz other ways not easy
@Dutch cuz other ways not easy
Oak saucer gallOP
The problem is that nextJS middleware doesn't support things like redis as far as I can tell
i found many tutorials in sec
@Dutch i found many tutorials in sec
Oak saucer gallOP
I was looking at this thread ; there are common import problems with the redis libraries as there is only a specific list of njs libs supported in the middleware: https://github.com/vercel/next.js/discussions/34179#discussioncomment-9850610
I saw that there is a npm runtime available in some bleeding edge versions but I'm trying to not get my team to use unstable software unless there's no other option
Is there really no way to just invoke a function for every route?
Dutch
you are looking easy way
node's app.use is a middleware tho
Oak saucer gallOP
We re not using uptash redis, we host our own. We need the usual redis libs like ioreris to work.
Upstash redis.is just an api wrapper not really connecting to a redis server
Dutch
just setup redis at your express backend, or whatever isnt it
@Dutch just setup redis at your express backend, or whatever isnt it
Oak saucer gallOP
I'm unsure what this means, can you elaborate?
@Oak saucer gall I'm unsure what this means, can you elaborate?
Dutch
what is your backend
@Dutch what is your backend
Oak saucer gallOP
I'm unsure what you mean, I'm using the nextjs development server. Do you mean the other databases?
@Oak saucer gall I'm unsure what you mean, I'm using the nextjs development server. Do you mean the other databases?
Dutch
setup a seperate backend and connect to redis, then connect to it from next api, not easy but good solution
@Dutch setup a seperate backend and connect to redis, then connect to it from next api, not easy but good solution
Oak saucer gallOP
I do not understand what advantage this provides to me.
@Oak saucer gall I do not understand what advantage this provides to me.
Dutch
i dont think you need a advice tbh
@Dutch i dont think you need a advice tbh
Oak saucer gallOP
I think this option is generally not feasible for a simple pre-route hook, which is one or two lines of code in most other frameworks I've worked with. I will wait for other suggestions. Thank you for your comments and clarification.