Deactivate internationalization for a specific route in Next.js - i18n feature

I'm currently utilizing the deufakt i18n localization plugin to translate my webpage, but I have a specific requirement to disable localization for my /blog route.

Essentially, what I want to achieve is:

mypage.com/es/anotherRoute -> mypage.com/blog (The es or any other language code should be removed)

However, the primary issue I am encountering is with building the following app.

The problem lies in the fact that the post in [slug] is undefined during prerendering, even though it should not be as it appears when logged using console.log.

[slug]

/* The JavaScript code snippet */
import ErrorPage from "next/error";
import { getStrapiURL, getPageData, getBlogPost } from "utils/api";
import Sections from "@/components/sections";
import Seo from "@/components/elements/seo";
import { useRouter } from "next/dist/client/router";
import BlogPost from "@/components/blog/blogPost";

const BlogPage = ({ post, allPosts }) => {
  const router = useRouter();
  if (router.isFallback) {
    return <div className="container">Loading...</div>;
  }
  return (
    <>
      {/* Add meta tags for SEO*/}
      <Seo metadata={post.metadata} />
      {/* Display content sections */}
      <BlogPost {...{ post, allPosts }} />
    </>
  );
};

export async function getStaticPaths() {
  const blogPosts = await (await fetch(getStrapiURL("/blog-posts"))).json();
  const paths = blogPosts.map((page) => {
    return {
      params: { slug: page.slug },
    };
  });

  return { paths, fallback: true };
}

export async function getStaticProps({ params, preview = null }) {

  const pageData = await getBlogPost(params.slug);
  const allPosts = await (await fetch(getStrapiURL("/blog-posts"))).json();

  if (pageData == null) {
    // Providing no props to the page will result in a 404 page
    return { props: {} };
  }

  return {
    props: {
      post: pageData,
      allPosts,
    },
    revalidate: 1,
  };
}

export default BlogPage;

My pages directory structure:

pages
├── [[...slug]].js
├── _app.js
├── _document.js
└── blog
    ├── [slug].js
    └── index.js

Answer №1

The i18n plugin configuration includes a ignoreRoutes property

i18n: {
    defaultLocale: 'en',
    locales: availableLocalesMap,
    ignoreRoutes: [
        '/blog/',
        '/public/'
    ],
},

UPDATE: This information is no longer valid, allowing us to approach the issue in a different way

You can refer to the discussion on Github posted by @neuroine for more insights:

https://github.com/vercel/next.js/discussions/28554

Answer №3

After some trial and error, I finally found a successful solution.

The modification I made was substituting

<Link href="/privacy-policy">

with

<Link locale={false} href="/en/privacy-policy">

This adjustment ensures that no additional language is added to the URL for my privacy page, keeping it in English at /en/privacy-policy. Additionally, by disabling /en as the default language, the URL automatically redirects to /privacy-policy.

Answer №4

Recently, I encountered a similar situation where I had to deactivate all specified locales except for the default one (different app instances have different default locales).

I managed to achieve this using the following code snippet:

export function checkDefaultLocale(req: NextRequest) {
   if (process.env.DEFAULT_LOCALE && process.env.DEFAULT_LOCALE !== req.nextUrl.locale) {
    return NextResponse.redirect(req.nextUrl.origin + '/404');
  }
}

Answer №5

When working on my project, I implemented a translation feature using i18n. However, not all pages were intended to be translated, leading to deployment errors.

If you are facing a similar issue, consider using Next.js 'redirects' feature as a solution. Here is how I resolved it:

async redirects() {
      return [
         {
            source: '/es/project/page',
            destination: '/project/page',
            permanent: false,
          },
      ]
}

For pages without translations, I simply redirected them to the original URL without a translation and set permanent: false for future translation integration.

Hopefully, this approach can assist you in overcoming your translation hurdles.

You can find more information about the solution here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Prevent unwanted bouncing and zooming on IOS10+ when using routing in VueJS

Currently, I am developing a Vue.js application that integrates with Three.js to display 3D models. I am using Vue.js with Vuetify as the framework and incorporating the Vue.js router. Due to the nature of displaying 3D models, I need to prevent zooming i ...

Node.js - Locate a specific parameter within an array that is nested within a JSON object, and retrieve the remaining

I am working with a Node.js API call that returns a JSON object. My goal is to extract the customer's phone number from this object using a specific function, like body.result.reservations[X of reserv.].client.phone, and retrieve parameters such as p ...

Enrolling JavaScript documents and connected inline programming

I need a solution for dealing with two arrays. The first array consists of URLs pointing to JavaScript files that I want to register using $.getScript(url); Next, the second array contains inline JavaScript commands that should be registered with $("html ...

Reveal the CSRF token to the client located on a separate domain

Utilizing the module https://www.npmjs.com/package/csurf to safeguard my public routes from cross-site request forgery. Due to the server and client being on separate domains, a direct method of passing the generated token to the client is not feasible. I ...

Upgrade personalized AngularJS filter from version 1.2.28 to 1.4.x

When working with a complex JSON response in AngularJS, I encountered the need to filter a deeply nested array within the data. The challenge arose when only displaying a subset of attributes on the screen, leading to the necessity of restricting the filte ...

Arranging arrangements in javascript

I am dealing with objects that contain the fields id and position. const items = [{id: 11, position: 1}, {id: 12, position: 2}, {id: 13, position: 3}, {id: 14, position: 4}, {id: 15, position: 5}, {id: 16, position: 6}]; These objects represent folders st ...

The ES6 alternative to require() when not using exports

When I utilize require(./filename), I am able to include and run the code within filename without any explicit export being defined inside filename. In ES6, what is the equivalent of this using import ? Appreciate it ...

Transferring data between sibling components in React/Next.js through prop drilling

I'm currently facing an issue where I need to pass a single value to a modal in another sibling component within NextJS. I am aware of using context for this purpose, but I find it quite complex to understand and the current structure doesn't sup ...

What is the best way to execute a randomly chosen function in JavaScript?

I need help running a random function, but I'm struggling to get it right. Here's what I have so far: <script> function randomFrom(array) { return array[Math.floor(Math.random() * array.length)]; } function randomchords(){ randomFrom ...

How can you pass an authorization token in a Next.js post request when using Django REST framework?

Is there a way to successfully pass a Django authorization token in Next.js using Axios? I attempted this method, but encountered a 404 error. let token = "Token 8736be9dba6ccb11208a536f3531bccc686cf88d" await axios.post(url,{ headers ...

Aptana - Expose the Declaration

After hearing rave reviews about Aptana being the best IDE for JavaScript, I decided to download it. I grabbed a project from GitHub, found a method call in the code, right clicked on it, and saw 'open declaration - F3'. However, when I tried bot ...

Guide on how to selectively add middleware such as multer to a fresh express router

For a previous project, I set up a router and utilized multer for handling file uploads. I was able to apply the multer middleware selectively on specific routes as shown below: var router = express.Router(); var multer = require('multer'); var ...

Ways to deactivate selecting rows in a datatable

Is there a way to deactivate the select feature specifically within datatables? An example of using ctrl+a for disabling select all function is available here https://i.stack.imgur.com/RQNXT.png ...

Issue with nested async functions

I am attempting to retrieve data from a view and then run another query using that retrieved data. The issue I'm facing is that my current implementation only returns empty objects like [{},{},{},{},{},{},{},{},{},{},{},{},{},{}] Any suggestions wou ...

Encountered a NextJS error during startup and building process: Assertion `(insertion_info.second) == (true)' failed

Out of the blue, my NextJS app is refusing to start or build, displaying the following error message: npm[213732]: c:\ws\src\env-inl.h:1041: Assertion `(insertion_info.second) == (true)' failed. 1: 00007FF7A493052F napi_wrap+109311 // ...

Having trouble implementing a cookie on the second domain using the first domain. Can't seem to get it to work properly

Currently, I am working on integrating ajax functionality with PHP. My main objective is to generate a cookie on the page where ajax call is made. The scenario involves two distinct domains - domain1.com and domain2.com. Essentially, the ajax code is imple ...

The query for Node.js using mysql is not defined

Recently, I've been working with Node.js and attempting to incorporate mysql in conjunction with nodejs. Specifically, I have written a query trying to retrieve numbers from a table: select numbers from TABLE, but the end result shows up as: "undef ...

Dynamically removing buttons with JQuery

I am trying to dynamically add buttons to a page based on an array, but I'm running into a problem. Whenever I add a new name to the array, it prints out all of the buttons instead of just the one I added. I need help figuring out how to erase all the ...

Can an icon be included in Material UI's DataGrid headers when the sorting direction is not defined?

In the DataGrid's API of Material UI, you can see how to include a sort icon for ascending and descending directions. By default, these icons are shown as arrow up and arrow down symbols but can be customized using props. However, my project requires ...

Is it possible for me to determine when all images have finished loading in order to update the isLoaded variable to true?

I am using the template below: <template> <div v-if='isLoaded'> <div @click='selectSight(index)' v-for='(sight, index) in sights'> <img :src="'https://maps.googleapis.com/maps ...