skip to Main Content

I am using nextjs 14 and just integrated next-intl for internationalization.

My Problem:

If I switch between the browse and my-items page, the fetch script, and the page rendering twice

My questions:
1, Why does it happen?
2, How can I fix it to render only once?

My folder structure looks like this:

app
├── [locale]
│   ├── items
│   │   ├── browse
│   │   │   └──page.tsx
│   │   ├── my-items
│   │   │   └──page.tsx
│   │   └──page.tsx
.   .
.   .
.   .

middleware.ts:

import { match } from '@formatjs/intl-localematcher';
import Negotiator, { Headers } from 'negotiator';
import { NextRequest } from 'next/server';
import createIntlMiddleware from 'next-intl/middleware';

// import { NEXT_LOCALE_NAME, locales, defaultLocale, Locales } from '@monorepo/shared';
const NEXT_LOCALE_NAME = 'NEXT_LOCALE';
const locales = ["en" , "de"];
const defaultLocale = 'en';
type Locales = typeof locales;

function getLocale(request: NextRequest): Locales[number] {
    try {
        const headers: Headers = Object.fromEntries(request.headers.entries());

        const languages = new Negotiator({
            headers,
        }).languages();

        return match(languages, locales, defaultLocale) as Locales[number]; // -> 'en-US'
    } catch (error) {
        return defaultLocale;
    }
}

export default async function middleware(request: NextRequest) {

    const dl = getLocale(request);

    const handleI18nRouting = createIntlMiddleware({
        locales,
        defaultLocale: dl,
    });

    const response = handleI18nRouting(request);

    return response;
}

export const config = {
    matcher: ['/((?!_next|api).*)']
};

app/[locale]/items/browse/page.tsx:

const getData = async () => {
    return fetch('https://browse-url', { 'cache': 'no-cache' });
}

export default async function Page() {
    const data = await getData();
    const dataJson = await data.json()

  return (
    <main>
      <h1>Browse Page</h1>
    </main>
  );
}

app/[locale]/items/my-items/page.tsx:

const getData = async () => {
    return fetch('https://my-items', { 'cache': 'no-cache' });
}

export default async function Page() {
    const data = await getData();
    const dataJson = await data.json()

  return (
    <main>
      <h1>My-items Page</h1>
    </main>
  );
}

Update: If I remove the top-level [locale], dev mode worked fine, but in prod its still double fetching the data.

2

Answers


  1. in middleware use

    return NextResponse.redirect(new URL('/dashboard', req.url));
    
    Login or Signup to reply.
  2. You can disable it in next.config.json file:

    module.exports = {
        reactStrictMode: false,
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search