Next.js Discord

Discord Forum

How to use more than one middleware?

Black carp posted this in #help-forum
Open in Discord
Black carpOP
I need to use more than one middleware in my nextjs 14 app router, because I need to do both:
- rewrite for part of the url param that shouldn't be exposed to the client
- and redirect for another part of the url param that MUST be exposed to the client

How can I do that? 🙂

6 Replies

he showed exactly what you want to do with app router
Black carpOP
I just went over his video and one issue I have is that I need in one middleware to do a rewite for every single request and in another middleware to do a redirect sometimes and I can't figure out hwo to do both with the same NextResponse object
you need to send conditional responses for both cases
Black carpOP
What does that mean?
Let me tell you a bit more about what I'm trying to accomplish:
It's a multi tenant app, I need to get the domain in server components so I wrapped my app with /[domain]/** directory and in my middleware I take the domain from the request object and do a rewrite with the domain in the pathname, this way the client isn't exposed to the domain in the pathname but the server comps are
Now I also need localization on each of the tenants so my app directory now should look like this /[domain]/[locale]/**, but to first test that the locale logic works I commented out all the domain related code and chnage the directory name to /[locale] and in the middleware I check if there's no locale in the pathname I add English (/en) by redirecting to it

When I implement one of the above (/[domain] or /[locale]) it works for that one specific use, but I try to stack both of them into a pathname like this /[domain]/[locale] where the domain is a middleware rewrite 100% of the times (so it won't be exposed to the client) and the locale is only sometimes a redirect and sometimes not a redirect (it's redirect and not rewrite because I need this one to be exposed to the client)
Black carpOP
My issue is that in the first middleware I need to rewrite on every single request which means I won't reach the next middleware in the chain