aralroca / next-translate

Next.js plugin + i18n API for Next.js 🌍 - Load page translations and use them in an easy way!
MIT License
2.66k stars 206 forks source link

App Router - Default locale without it's name on url #1155

Open mbaldas opened 1 year ago

mbaldas commented 1 year ago

What version of this package are you using? 2.5.3 And using 2.6.0 for next-translate-plugn

What happened? I'm having trouble implementing i18n into Next 13 app router I set my pages under: app/[lang]/example/[slug] Everything works great when I have a route with the lang explicitly on the url, for example localhost:3000/fr/example/slugish-url-item/ works with FR translations localhost:3000/en/example/slugish-url-item/ works with EN translations

The problem is, in my case the /en/ should be omitted and treated like the default locale So if I go to: localhost:3000/example/slugish-url-item/ it should open the page with the EN translations But the problem is that it just redirects to my 404 page, assuming Next couldn't find this page on the app router

What would be the solution to having a default locale that's omitted on the URL using app router?

My i18n.js file on the root folder module.exports = { locales: ['en', 'fr'], defaultLocale: 'en', localeDetection: false, pages: { '*': ['global'], }, }

My middleware.ts

import { NextResponse } from 'next/server'

const shouldProceed = (pathname) => {
  if (pathname.startsWith('/_next') || pathname.includes('/api/')) {
    return false
  }
  return true
}

export async function middleware(request) {
  const { locale, pathname } = request.nextUrl

  if (!shouldProceed(pathname)) return

  // If the locale is not explicitly specified or is 'en', redirect to '/'
  if (!locale || locale === 'en') {
    if (pathname === '/') {
      return NextResponse.rewrite(request.nextUrl) // No redirection needed for '/'
    }

    // Redirect '/en/' to '/'
    if (pathname === '/en/') {
      const response = NextResponse.redirect(new URL('/', request.url))

      // Remove 'NEXT_LOCALE' cookie for '/en/'
      response.cookies.delete('NEXT_LOCALE', { path: '/' })

      return response
    }
  }

  request.nextUrl.searchParams.set('lang', locale)

  return NextResponse.rewrite(request.nextUrl)
}
mnaser commented 1 year ago

@mbaldas I'm running into a similar issue, did you end up getting some answer or idea for this?

mrkhedri commented 11 months ago

@mnaser @mbaldas The same issue. Has anyone found a solution or trick to resolve it in the middleware file?

lucaslosi commented 3 months ago

bump