Getting URL parameters in NextJS when using Custom Document can be achieved by accessing the `ctx`

Currently, I am utilizing NextJS for generating SSR pages that are language-specific. I want to specify the lang property to indicate the language of the text.

Here's what I have done so far:

import Document, { Html, Head, Main, NextScript } from "next/document"
import Router from "next/router"

class MyDocument extends Document {
  render() {
    const { lang } = Router.router.query
    return (
      <Html lang={lang}>
        <Head />
        <body className="antialiased text-white text-base font-sans">
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

export default MyDocument

However, Router.router is always null when using a Custom Document (_document.js). Could there be an alternative method to access the URL parameters/query while working with a Custom Document?

Answer №1

My solution involved the following code:

import Document, { Html, Head, Main, NextScript } from "next/document"

class MyDocument extends Document {
  render() {
    const { lanaguage } = this.props.__NEXT_DATA__.query
    return (
      <Html lang={lanaguage}>
        <Head />
        <body className="antialiased text-white text-base font-sans">
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

export default MyDocument

I am questioning whether using this.props.__NEXT_DATA__ is considered bad practice. However, it does contain the necessary information for my purposes.

Answer №2

Ever since the release of Next.js version 10, utilizing the integrated i18n routing, Next.js will automatically assign the lang attribute to the document.

Quoting from the official documentation:

Given that Next.js can determine the user's language preference upon visiting a page, it will then proceed to include the lang attribute within the <html> tag by default.

While Next.js may not recognize page variants, it is your responsibility to incorporate the hreflang meta tags using the next/head component. For further information on hreflang, refer to the Google Webmasters documentation.

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

Pulling data from a MySQL database using AJAX and PHP to convert it into a JavaScript variable, resulting in

I am attempting to retrieve MySQL data using PHP, convert it to JSON, and then pass it into my JS variables for Chart.js. The JSON generated by PHP appears correct. However, when trying to access the data within my variables, the console is displaying them ...

The component next/image is experiencing issues when used in conjunction with CSS

I struggled to create a border around an image because the custom CSS I wrote was being overridden by the Image component's CSS. Despite trying to leverage Tailwind and Bootstrap to solve the problem, my efforts were unsuccessful. Now, I am at a loss ...

Using Jquery and css to toggle and display active menu when clicked

I am trying to create a jQuery dropdown menu similar to the Facebook notification menu. However, I am encountering an issue with the JavaScript code. Here is my JSFiddle example. The problem arises when I click on the menu; it opens with an icon, similar ...

Listener for clicking on a marker in Google Maps

Trying to add a click event to Google Map markers in my Cordova app has proven to be quite challenging. The recommended ways mentioned in the documentation don't seem to work, unless I make the marker draggable - which is not an option for me. It seem ...

Refreshing an AJAX call automatically in Knockout JS

Greetings everyone! I'm currently working on setting up a simple setInterval function to automatically refresh my data every minute. The line that is giving me trouble is: setInterval(incidentViewModel.fetchdata,60000); I also attempted this: windo ...

Having trouble getting a React app integrated with WordPress on an NGINX server to function properly over HTTPS?

I am currently in the process of developing a React application that integrates with a WordPress site. The setup I am aiming for is as follows: When users visit example.com, they will be directed to my React app. If they navigate to example.com/blog, they ...

Switch up image origin when image reaches screen boundary

I am trying to create a DVD screensaver with changing images each time it hits the edge, but I can't seem to get it to work. I've attempted using the code snippet below: var img = document.getElementById("myImage"); img.src = 'img/new-image. ...

Testing actual HTTP requests in unit and integration tests with AngularJS

Attempting a request that was not mocked using $httpBackend.when in an Angular 1.x unit/integration test will lead to an error: Error: Unexpected request: GET /real-request Is there a way to perform actual HTTP requests with ngMock and the Karma+Jasmin ...

I have successfully implemented ngCordova local notifications, but now I am looking for a way to make it trigger for each individual

Is there a way to trigger a notification on every logged-in user's mobile device when a value is changed and saved in Firebase? Currently, I am able to send a local notification using ngCordova when a user enters text in an ionicPopup with textarea. H ...

Challenges encountered with the "load" event handler when creating a Firefox Extension

I am currently troubleshooting a user interaction issue with my Firefox extension. The tasks that my extension needs to complete include: Checking certain structures on the currently viewed browser tab Making backend server calls Opening dialogs Redirect ...

My server keeps crashing due to an Express.js API call

I'm completely new to express.js and API calls, and I'm stuck trying to figure out why my server keeps crashing. It works fine the first time, rendering the page successfully, but then crashes with the error: TypeError: Cannot read property &apo ...

React components are failing to display data as expected

I need to display certain data based on the id provided in the url. When I use console.log() with res.json, I can see the data but I'm unsure how to pass it to the 'articleComponent'. const Articles = () => { const query = (id) => ...

Issue retrieving nested object in NextJS

view-component.js const ViewComponent = () => { const route = useRoute(); //All good here const data = fetchData(); console.log(data); //Issue arises with this line const profileData = data.profile; console.log(profileData) ...

Problem with Metadata Changes in Next.js: Metadata Getting Reset After Rebuilding .next Directory

I've run into a problem while trying to customize metadata in my Next.js app. Even though I can successfully make changes to the metadata in my layout.tsx file, these modifications are not showing up in the console output. Additionally, whenever I del ...

Mapping through multiple items in a loop using Javascript

Typescript also functions Consider an array structured like this const elementList = ['one', 'two', 'three', 'four', 'five'] Now, suppose I want to generate components that appear as follows <div&g ...

Leveraging AJAX for fetching files on the identical server

Just starting out with HTML and AJAX programming, so let's give it a shot: I've developed a website that populates a table with content from an external txt file (content.txt). The text file is hosted on a Windows 2003 webserver in the C:\I ...

Is a webpage's sluggishness in Internet Explorer due to its lengthy page structure causing issues while loading quickly on other browsers?

My application has a page that is particularly long, around 8Mb of source HTML mainly comprised of tables. I am aware that this indicates poor architecture, but unfortunately, I am unable to make immediate changes due to certain constraints. In most brows ...

Trigger a popup using the javascript .link() method

I am currently using ag-grid to present JSON data. When the values are located within nested objects, I have to utilize a valueGetter from the grid API to map to the appropriate value. The value getter returns a value for each row and the grid matches it t ...

Dynamic routing in Next.js expands upon the current path

With my Next.js blog utilizing Strapi CMS, I am attempting to arrange the posts by their respective categories. I have set up a dynamic route for categories [id].js and have implemented getStaticPaths as shown below: export async function getStaticPaths() ...

Are you unsure whether to use Ajax or jQuery? If you need assistance in adding parameters to

Currently delving into ajax/jQuery and encountering some hiccups. Here's the code snippet: .click(function() { var period = 'ALL'; if ($('#registerat input:checked').val() != 'ALL') period = ...