Help for redirecting using middleware when landing on the page
Answered
Max posted this in #help-forum
MaxOP
Hi !
I am implementing i18n for the first time. I basically use a dynamic param [lang] in the routing.
I need to redirect on
I added a
Any help or advise is appreciated !
Thanks 😃
I am implementing i18n for the first time. I basically use a dynamic param [lang] in the routing.
I need to redirect on
/en or /fr when landing on the website...I added a
middleware.ts in the app router. But It seems doing nothing, and I struggle to debug it since nothing happens or log into the consoles.Any help or advise is appreciated !
Thanks 😃
23 Replies
can you show your
middleware.tsand are you sure that you are matching the right paths (can check by console.log at the start)
You dont add middleware.ts inside the app folder btw
Answer
You need to put in the project root
Where your package.json is
MaxOP
Hi !
import {NextRequest} from 'next/server'
// I just took this code from the documentation and updated it a bit.
// removed the logs but i was trying to log things from the middleware to see how it works and behaves while navigating, but nothing happens...
export function middleware(request: NextRequest) {
let locale = ['en', 'fr']
const {pathname} = request.nextUrl
const pathnameHasLocale = locale.some(
locale => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
)
if (pathnameHasLocale) return
request.nextUrl.pathname = `/fr/${pathname}`
return Response.redirect(request.nextUrl)
}
// This I don't get what is it for... ? To match only a specific path ?
export const config = {
matcher: [
// Skip all internal paths (_next)
'/((?!_next).*)',
// Optional: only run on root (/) URL
// '/'
],
}and as @Clown said, is this in the right folder and name
@Clown You dont add middleware.ts inside the app folder btw
MaxOP
Oh Okay ! I think I tried moving it, but i'll do another try
it was indeed in my app directory
and it now works (after you moved it back)?
MaxOP
Because in the documentation it seems to say to put it in the app dir....
https://nextjs.org/docs/app/building-your-application/routing/middleware
https://nextjs.org/docs/app/building-your-application/routing/middleware
same level doesn't mean inside
- app
- page.ts
- middleware.ts
- page.ts
- middleware.ts
@riský same level doesn't mean inside
MaxOP
Oh yes.... haha non native english speaker... haha
oke let me try it out
Page.ts is below in hierarchy while middleware.ts is at the same level as app
MaxOP
OOOOO it works
thank you so much ! I struggled on this yesterday, and it was just my musunderstanding of english lol
Thanks for answering that fast also ! 🙂
