Next.js Discord

Discord Forum

Catching global route changes in Nextjs 13

Unanswered
Bolognese posted this in #help-forum
Open in Discord
Avatar
BologneseOP
I'd like to catch an event when my route has changed. Every time the route changes, I'd like to check the URL for a specific string, and if it contains a specific string, I'd like to handle that and do something.

I'm finding this difficult to do with Nextjs 13 and its app router implementation.

In an older version of Next (and its Pages Router), I would've used a useEffect with a dependency for useRouter to capture the event in _app.js. Since my layouts and top-level components are server components, I cannot use useEffect. I also realize that my top page.tsx and layout.tsx code only execute during their initial load. I am not seeing code re-render there on each route (although I would not expect it to reliably without using useEffect)

How can I best capture route changes, globally using App Router and Nextjs 13?

11 Replies

Avatar
European sprat
you can try using middleware but client side navigation may not hit middleware
Avatar
BologneseOP
Sorry -- I should've added that I cannot use middleware because my app, at this time, requires node functions and has dependencies that prevent me from using edge. TMK -- middleware must run on edge.

Actually -- I'll try this just to be certain but yes i also share your same concern.
Avatar
European sprat
yeah there are ways around it though like fetching a route handler in middleware
Avatar
BologneseOP
do you know of any examples you could link?
Avatar
European sprat
i don't know what you're doing that requires node dependencies but for me i wanted to get the user from db but can't due to edge runtime so i made an /api/user route handler where, from middleware, i fetch it and return the user object to middleware
so in that route handler you can do all the nodejs runtime stuff you need to then return json to middleware
but of course it all depends on what you need to do in middleware to begin with
Avatar
BologneseOP
interesting. yeah, i had a similar issue that caused me to stop using middleware for auth.

all i need to do today in the middleware is check a route. If a specific route string exists, I want to update a context. does that sound doable?
Avatar
European sprat
If you're talking react context then no that won't work, you can't update that from middleware. Also middleware won't run if things are loaded and client is navigating client side
Avatar
BologneseOP
I did confirm that middleware gets hit every time, for my specific implementation. I don't have any custom client side routing, and rely on next/navigation entirely for everything so potentially that's why.

however yes, just realized i definitely can't use react context.
Avatar
Irish Terrier
@European sprat @Bolognese Hi! I've noticed that middleware is not always hit during client side navigation; is there any documentation where this is explained?