What is the correct way to integrate the Ant Design library with Next.js for seamless server-side rendering?

I duplicated the official Next.js example using Ant Design at this link: https://github.com/vercel/next.js/tree/canary/examples/with-ant-design

After cloning, I proceeded with npm install to install all dependencies. Then, I ran npm run dev to check if everything was working fine. Subsequently, I used npm run build to build the Next.js app and executed npm run start to run the built app on localhost.

The issue arose when I went to the network tab, selected the localhost page, and previewed it from the preview tab. The Ant Design styles were not being applied properly with server-side rendering, resulting in no visible styles at all initially. It took about half a second for the Ant Design CSS to finally apply, which is not the desired outcome.

Is there a way to properly implement Ant Design with Next.js server-side rendering?

Answer №1

If you're seeking a way to optimize the loading of CSS on your website, consider inlining the CSS directly into the HTML. This can help speed up the rendering process by eliminating the need for the browser to make separate requests for CSS resources.

While official support for this feature is still pending, there is a workaround available. You can check out more details and updates on this matter at https://github.com/vercel/next-plugins/issues/364.

In the meantime, you can implement the workaround mentioned in https://github.com/vercel/next-plugins/issues/238. I have personally tested this solution and can confirm that it works effectively.

To inline the CSS, you will need to create a file named _document.js within the pages folder. Copy and paste the code below into this file:

import Document, { Head, Main, NextScript } from 'next/document';
import fs from 'fs';
import path from 'path';

class CustomNextHead extends Head {
  // Potential workaround until built-in support is added
  getCssLinks({ allFiles }) {
    return allFiles
      .filter((file) => file.endsWith('.css'))
      .map((file) => (
        <style
          key={file}
          nonce={this.props.nonce}
          dangerouslySetInnerHTML={{
            __html: fs.readFileSync(path.join('.next', file), 'utf-8'),
          }}
        />
      ));
  }
}

export default class MyDocument extends Document {
  render() {
    return (
      <html lang="en">
        <CustomNextHead />
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    );
  }
}

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

Changing the Flash message to an Alert message in Symfony2: A step-by-step guide

I've encountered a problem where the success message from an action method in Symfony2 Controller appears as a flash message, but I need to display it as an alert or dialogue message according to requirements. I have attempted various solutions witho ...

Avoid the rendering of child elements in React

How can I skip rendering children in React? I want to enclose existing DOM nodes on a page within a React component. I need to render the frame only, excluding the static content which already exists as pre-existing DOM nodes. Is there a way to achieve t ...

What are the best practices for utilizing databases with both Javascript and JSF frameworks?

I am currently following the recommendations provided by @BalusC, with additional guidance available here. (The reason I'm posting this here is because it's not related to my previous question). My goal is to retrieve data from my database and d ...

Angular 6 TypeScript allows for efficient comparison and updating of keys within arrays of objects. By leveraging this feature

arrayOne: [ { id: 1, compId: 11, active: false, }, { id: 2, compId: 22, active: false, }, { id: 3, compId: 33, active: false, }, ] arrayTwo: [ { id: 1, compId: 11, active: true, }, { id: 2, compId: 33, active: false, ...

How to use Javascript to fetch HTML content from an external website

Is it possible to access and retrieve scores from for a specific week using AJAX or JSON technology? Each game on the website seems to have a unique class which could make retrieving score information easier. Any guidance or assistance would be greatly ap ...

Mastering the Art of SQL Submission with PHP Ajax Requests

I've encountered an issue with a form that, upon validation, triggers two Ajax requests before submitting the data to create an entry in a MySQL database. The Ajax requests generate URLs to Google Documents using upload.php. However, when certain unk ...

The Autocomplete field's label remains visible even after the form is submitted

I am currently developing a feature that allows users to select an option in the Autocomplete component. In the parent component, I pass these props: const filterDropdownConfig: FilterSelectAutocomplete = { data: scenariosList, label: { className: &apos ...

Using query parameters in Angular to interact with APIs

One scenario involves a child component passing form field data to a parent component after a button press. The challenge arises when needing to pass these fields as query parameters to an API endpoint API GET /valuation/, where approximately 20 optional p ...

Error message appearing repeatedly and submit button functioning only after second click

I am currently working on my CS50 Final Project, where I am in the process of designing a web app using Flask. Specifically, this issue arises in the login/register page where I am attempting to verify if the username is already taken (through jsonify) and ...

Unable to use .ajax within autocomplete function

I've been struggling for days to make the jQuery autocomplete feature work. Currently, I am able to type in the textbox and see exactly what I want, but the issue arises when I click on the desired option - it does not show up in the textbox. I suspec ...

The React router implementation is resulting in a blank index page when using Next.js

As I work on my website, I want to ensure that users are directed to a specific page upon opening the site. The destination of the users depends on whether they have logged in or not. However, I am facing an issue with the router as it is not redirecting t ...

Using AJAX to submit a single form

Within my HTML view, I have multiple forms that are displayed using a PHP foreach loop. One of the form examples is as follows: <form method="POST" class="like-form-js"> <input type="hidden" name="post_id" value="<?= $post['i ...

Authentication of users in Django and NextJS

Looking for guidance on implementing user authentication in a project that combines Django Rest Framework as the backend and NextJS as the React frontend. How can these two technologies be integrated seamlessly? We are also considering building a mobile a ...

The Angular bootstrap popover vanishes as soon as the mouse hovers over it

Currently, I am facing an issue with an angular bootstrap popover on some text. The problem arises when the user tries to click on a link inside the popover as it disappears. Additionally, when changing from one popover to another, the previous one does no ...

Customized slider in jQuery UI allowing users to select height using a scaled ruler

Currently, I am tackling a challenging math problem related to adjusting the height selector input. Essentially, I have implemented a jQuery UI slider for choosing a height. It operates in inches and ranges from 0 to 120 (equivalent to 10 feet in height). ...

Learn the ins and outs of Ember.js with our comprehensive tutorial and guide. Discover solutions to common issues such as DS

Learning Ember has been a challenging experience for me. The guide I am using seems to be lacking important information that I need. I keep encountering two specific errors: Uncaught Error: Ember.State has been moved into a plugin: https://github.com/e ...

Issue with reactivity not functioning as expected within VueJS loop without clear explanation

Struggling with implementing reactivity in vue.js within a loop? The loop renders fine, but firing an event updates the content without visibly rendering the data on the page. The latest version of vue.js is being used with bootstrap and jquery. Despite a ...

Prevent further execution upon callback in an AJAX request by stopping the click event function

When the function myClick() is called within itself instead of myLoad() on the first click, it leads to double execution of myClick() on the second click. => This results in two consecutive executions of the click event for #myBtn with just one click. ...

Guide on transferring data from an API using mapped React hooks

I am working with react hooks and attempting to pass a value to the delete function and execute the put function <Fab aria-label="delete" className={classes.fab} value={vacation.id} ...

React-Redux Error: The function this.props.AppendCharacter is not defined

I have been looking for a solution to my issue but couldn't find anything that matches it. I am working on creating a calculator app using React & Redux, and whenever I click on one of the number buttons, I receive an error message saying "this.props. ...