How to set up dynamic lang that matches the current locale in Next.js app router

Hi there!

I'm moving my project to the app router and I'm not entirely sure how to make Prismic work to set RootLayout lang dynamically for me based on the current locale

export default function RootLayout({children}: { children: React.ReactNode }) {
    return (
        <html lang="en-gb"> // this here needs to be dynamic, if I switch to German I expect 'de-de' here instead
        <body className={classNames(figtree.className, 'antialiased bg-white text-gray-600 selection:bg-green-200')}>
        <GlobalsProvider>
            <CurrencyProvider>
                {children}
            </CurrencyProvider>
        </GlobalsProvider>
        <PrismicPreview repositoryName={repositoryName}/>
        </body>
        </html>
    )
}

And here is my middleware:

import {NextRequest, NextResponse} from 'next/server';
import {createClient} from '@/prismicio';

export async function middleware(request: NextRequest) {
    const client = createClient();
    const repository = await client.getRepository();

    const locales = repository.languages.map(lang => lang.id);
    const defaultLocale = 'en-gb';

    // Check if there is any supported locale in the pathname
    const {pathname} = request.nextUrl;

    const pathnameIsMissingLocale = locales.every(
        locale => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
    );

    // Redirect to default locale if there is no supported locale prefix
    if (pathnameIsMissingLocale) {
        return NextResponse.rewrite(
            new URL(`/${defaultLocale}${pathname}`, request.url)
        );
    }
}

export const config = {
    matcher: ["/((?!api|_next/static|_next/image|robots.txt|images|icon).*)"],
};

I'm using /src/ directory with a lang param, example path:
src/app/[lang]/page.tsx

How can I make these two work together to inject current locale into my lang attribute?

Hello!

Based on my understanding of the Next.js documentation, it appears that you can place your rootLayout component inside app/[lang]/layout.tsx in your project structure. You can refer to the section provided in this link: Next.js Internationalization Routing Overview.

By doing this, I think you should be able to accept { params: { lang } } in the exported default function for the layout.

Best regards,

Samuel

Just did a quick test and it seems to work:

Hmm, I did try that to start with but then Next complained there is no root layout and dropped 404 instead hence why I asked here.

I tried it again and it actually worked, I must have missed something somewhere.
Thanks!

No worries, glad it worked out :slight_smile: