Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Critical dependency: the request of a dependency is an expression when using App dir. #1029

Closed
guillermo-avalos opened this issue Apr 18, 2023 · 28 comments

Comments

@guillermo-avalos
Copy link

guillermo-avalos commented Apr 18, 2023

Using Next-Translate v2.0.5 with Next.js v13.3.
Node v19.9, npm v9.6.4

While trying to setup Next-Translate following the instructions in this post: https://dev.to/aralroca/i18n-translations-in-nextjs-13s-app-dir-for-serverclient-components-4ek8 and copying exactly the code form the CodeSanbox example, I'm getting this error in the server console:

Critical dependency: the request of a dependency is an expression

I've been using Next-Translate for several projects but this is the first time with the new App router.

My next.config.js file is as follows:

const nextTranslate = require('next-translate-plugin')
module.exports = nextTranslate({
experimental: { appDir: true },
})

middleware.js:

import { NextResponse } from 'next/server'
import i18n from './i18n'

export function middleware(request) {
  const locale = request.nextUrl.locale || i18n.defaultLocale
  request.nextUrl.searchParams.set('lang', locale)
  request.nextUrl.href = request.nextUrl.href.replace(`/${locale}`, '')
  return NextResponse.rewrite(request.nextUrl)
}

I18n.js:

module.exports = {
  locales: ['es', 'en'],
  defaultLocale: 'es',
  pages: {
    '*': ['common'],
  },
}

While trying to navigate to the main page I just get a 404 error. /es or /en doesn't change a thing.
Any ideas?

@guillermo-avalos
Copy link
Author

The 404 error went away after placing both layout.jsx and page.jsx inside a [locale] folder after reading Next's docs.
It kinda works, but Node seems to leak memory and spawning several instances. The server console still shows the error.

@vdjurdjevic
Copy link

I am having the same issue.

@kasuta96
Copy link

kasuta96 commented May 1, 2023

Critical dependency: the request of a dependency is an expression

Same!
The 404 error is occurring because Next.js 13.3 has made some changes to routing (13.2 works perfectly fine).
like @guillermo-avalos said. After move to inside [locale] folder, it does work, but it doesn't seem to be stable.

Btw, to use next-translate 2.0.5, I believe we should stick with Next.js 13.2 for now.

@nirtamir2
Copy link

Same problem here. next 13.4 & next-translate 2.0.5.
The i18n loads only on the client, and not on the server.

Also the code to sync date and lang cause runtime error:

Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading 'length')
"use client";

import { useEffect } from "react";
import dayjs from "dayjs";
import "dayjs/locale/en";
import timezone from "dayjs/plugin/timezone";
import utc from "dayjs/plugin/utc";
import useTranslation from "next-translate/useTranslation";

interface Props {
  children: JSX.Element;
}

dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.tz.guess();

export const DateProvider = ({ children }: Props) => {
  const { lang } = useTranslation();

  useEffect(() => {
    dayjs.locale(lang);
  }, [lang]);

  return children;
};

Is there a way to HACK it somehow (even losing ssr) until we have a fix?

@alvesvin
Copy link

This is a warning from webpack. It seems webpack doesn't like imports with unpredictable paths at build time used by the default loader in next-translate-plugin. I don't know if it's really the case but it seems omitting overwriteLoadLocales still works.

@alvesvin
Copy link

Related aralroca/next-translate-plugin#9

@aralroca
Copy link
Owner

I tried to reproduce it in the latest version and I can't reproduce it. Maybe is solved with this related issue: aralroca/next-translate-plugin#32 Can you confirm that now is working for your in the latest version? Thanks!

@joaopedrodcf
Copy link

I'm also facing the same issue I'm currently using "next": "13.4.7" and "next-translate": "2.4.4" don't have a codesanbox prepared yet but here are the things I did:

This is what appears on my terminal:
image

And in the browser:
image

I tried to follow the docs and this article: https://dev.to/aralroca/i18n-translations-in-nextjs-13s-app-dir-for-serverclient-components-4ek8

middleware.ts

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import i18n from './i18n';

// /es/page-name -> rewrites to -> /es/page-name?lang=es
export function middleware(request: NextRequest) {
    const locale = request.nextUrl.locale || i18n.defaultLocale;
    request.nextUrl.searchParams.set('lang', locale);
    return NextResponse.rewrite(request.nextUrl);
}

i18n.js

module.exports = {
    locales: ['en', 'pt', 'fr'],
    defaultLocale: 'en',
    pages: {
        '*': ['common'],
    },
};

next.config.mjs

// @ts-check
import bundleAnalyzer from '@next/bundle-analyzer';
import nextTranslate from 'next-translate-plugin';

const analyzeEnabled = process.env.ANALYZE === 'true';

/** @type {import("next").NextConfig} */
const config = {
    reactStrictMode: true,
    swcMinify: true,
    webpack: (config, { isServer, webpack }) => {
        return config;
    },
};

const withBundleAnalyzer = bundleAnalyzer({
    enabled: analyzeEnabled,
});

export default withBundleAnalyzer(nextTranslate(config));

My app dir is currently like this:
image

@aralroca
Copy link
Owner

The 404 probably is for the middleware, I need to update this article, but after next.js 13.2 the middleware with i18n has an issue reported in Next.js but we updated using dynamic router [lang]. Probably you can remove the middleware, is not needed now to add the lang param and rewrite of the middleware is causing a 404 for this Next.js bug

@zakidze
Copy link

zakidze commented Jul 10, 2023

any solotion of this?????

@rolandjlevy
Copy link

@aralroca is there any solution for this problem? Can you help?

When I add loadLocaleFrom for the fallback, I get the same error: Critical dependency: the request of a dependency is an expression and can't find any solution for it. Is it a bug?

I am using next v12.2.5 and next-translate v2.4.4 and next-translate-plugin v2.4.4

This is what I added to the config. When I remove it, the error dissapears:

loadLocaleFrom: async (lang, ns) => {
    const defaultLocale = 'en-gb';
    const defaultNs = await import(`./locales/${defaultLocale}/${ns}.json`);
    if (lang === defaultLocale) return defaultNs;
    const localNs = await import(`./locales/${lang}/${ns}.json`);
    return { ...defaultNs, ...localNs };
}

I get the same error when adding this version too:

loadLocaleFrom: async (lang, ns) => {
    const defaultLocale = 'en-gb';
    const defaultNs = await import(
      `./locales/${defaultLocale}/${ns}.json`
    ).then((x) => x.default);
    if (lang === defaultLocale) return defaultNs;
    try {
      const localeNs = await import(`./locales/${lang}/${ns}.json`).then(
        (x) => x.default
      );
      return { ...defaultNs, ...localeNs };
    } catch (e) {
      return defaultNs;
    }
}

@LagoonProject
Copy link

I have the same problem, using "next" v13.4.9, and "next-translate" v2.5.2.

- wait compiling...
- warn ./node_modules/next/dist/pages/_app.js
Critical dependency: the request of a dependency is an expression

I don't have the 404 error though, since I moved the middleware.ts to the 'src' folder on the same level as 'app' folder.

@b-vetter
Copy link

b-vetter commented Aug 15, 2023

I have the same problem. All pages inside the [lang] folder return a 404 and the warning "Critical dependency: the request of a dependency is an expression.
Is there already a solution how to fix it?

And is it related to #1131 and will be fixed with the next release?

next 13.4.16
next-translate 2.5.3
next-translate-plugin 2.5.3

@rolandjlevy
Copy link

rolandjlevy commented Aug 19, 2023

@aralroca I found a solution 😀

In case this helps someone else having this problem. The code below works for me and I am no longer getting the error: Critical dependency: the request of a dependency is an expression

I am using next v12.2.5 and next-translate v2.5.2 and next-translate-plugin v2.5.2

in i18n.js:

 loadLocaleFrom: (lang, ns) => {
    const defaultLocale = 'en-gb';
    const defaultNs = require(`./locales/${defaultLocale}/${ns}.json`);
    if (lang === defaultLocale) return Promise.resolve(defaultNs);
    const localNs = require(`./locales/${lang}/${ns}.json`);
    return Promise.resolve({
      ...defaultNs,
      ...localNs,
    });
  },

@mirik999
Copy link

I'm also facing the same issue I'm currently using "next": "13.4.7" and "next-translate": "2.4.4" don't have a codesanbox prepared yet but here are the things I did:

This is what appears on my terminal: image

And in the browser: image

I tried to follow the docs and this article: https://dev.to/aralroca/i18n-translations-in-nextjs-13s-app-dir-for-serverclient-components-4ek8

middleware.ts

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import i18n from './i18n';

// /es/page-name -> rewrites to -> /es/page-name?lang=es
export function middleware(request: NextRequest) {
    const locale = request.nextUrl.locale || i18n.defaultLocale;
    request.nextUrl.searchParams.set('lang', locale);
    return NextResponse.rewrite(request.nextUrl);
}

i18n.js

module.exports = {
    locales: ['en', 'pt', 'fr'],
    defaultLocale: 'en',
    pages: {
        '*': ['common'],
    },
};

next.config.mjs

// @ts-check
import bundleAnalyzer from '@next/bundle-analyzer';
import nextTranslate from 'next-translate-plugin';

const analyzeEnabled = process.env.ANALYZE === 'true';

/** @type {import("next").NextConfig} */
const config = {
    reactStrictMode: true,
    swcMinify: true,
    webpack: (config, { isServer, webpack }) => {
        return config;
    },
};

const withBundleAnalyzer = bundleAnalyzer({
    enabled: analyzeEnabled,
});

export default withBundleAnalyzer(nextTranslate(config));

My app dir is currently like this: image

did you solve this problem ? i got the same error ((

@csexplorer
Copy link

the same issue!!!!

@b-vetter
Copy link

@aralroca I found a solution 😀

In case this helps someone else having this problem. The code below works for me and I am no longer getting the error: Critical dependency: the request of a dependency is an expression

Tested and doesn't work in my environment. Still the same error/warning.

@roland-cromwell
Copy link

@aralroca I found a solution 😀
In case this helps someone else having this problem. The code below works for me and I am no longer getting the error: Critical dependency: the request of a dependency is an expression

Tested and doesn't work in my environment. Still the same error/warning.

@b-vetter can you share the contents of your i18n.js and next.config,js files?

@b-vetter
Copy link

@roland-cromwell

i18n.js

module.exports = {
    locales: ["en", "de"],
    defaultLocale: "en",
    pages: {
      "*": ["common"],
      "/[lang]": ["home"]
    },
    loadLocaleFrom: (lang, ns) => {
      const defaultLocale = 'en';
      const defaultNs = require(`./locales/${defaultLocale}/${ns}.json`);
      if (lang === defaultLocale) return Promise.resolve(defaultNs);
      const localNs = require(`./locales/${lang}/${ns}.json`);
      return Promise.resolve({
        ...defaultNs,
        ...localNs,
      });
    }
  };

next.config.js

/** @type {import('next').NextConfig} */

const nextTranslate = require('next-translate-plugin')

const dns = require("dns");
dns.setDefaultResultOrder("ipv4first")

const nextConfig = nextTranslate({
  images: {
    domains: ['avatars.githubusercontent.com', 'avatar.vercel.sh']
  },
  experimental: {
    appDir: true,
    serverComponentsExternalPackages: ['@tremor/react']
  },
  async headers() {
    return [
      {
        source: "/api/:path*",
        headers: [
          // some header configuration
        ],
      }
    ]
  },
});

module.exports = nextConfig;

@abelchee
Copy link

I got the same error in https://github.com/aralroca/next-translate/tree/master/examples/with-app-directory when using next 13.4.19

next 13.4.7 works fine in the example

image

@cmaerz
Copy link

cmaerz commented Aug 29, 2023

Don't know whats happening there, but when I just do this:
image
It works fine somehow?! Even with 13.4.19

@abelchee
Copy link

Don't know whats happening there, but when I just do this: image It works fine somehow?! Even with 13.4.19

It doesn't work for me

@b-vetter
Copy link

b-vetter commented Aug 29, 2023

I got the same error in https://github.com/aralroca/next-translate/tree/master/examples/with-app-directory when using next 13.4.19

next 13.4.7 works fine in the example

Works also for me with 13.4.7 on my local machine but not on Vercel. There i get still 404 or 500 and some errors inside the log.
So is it a problem at next-js? When can we expect a fix on newer versions?

@bluelakee02
Copy link

I created a fix aralroca/next-translate-plugin#72
Here is a patch if somebody needs it right away https://github.com/bluelakee02/next-translate-plugin-patch

@bluelakee02
Copy link

@aralroca OK, now this can be probably closed

@aralroca
Copy link
Owner

@aralroca OK, now this can be probably closed

Sure 😊 people, now is already solved in 2.6.1 thanks to @bluelakee02

@AndryKK
Copy link

AndryKK commented Nov 1, 2023

@bluelakee02
Copy link

@AndryKK I deleted it, since it is in the 2.6.1 version already. The patch solves one problem, but in the end, I ended up implementing my own useLocales custom solution, which works on 13 with approuter

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests