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

Streaming data from a MongoDB database in a serverless Next.js application

Currently, I am referring to these resources in order to develop my Next-Mongo app without relying on a NodeJS server: https://www.mongodb.com/developer/how-to/nextjs-with-mongodb/ I have a question regarding data streaming. Is it possible to achieve rea ...

Dynamic autocomplete feature with AJAX integration for filtering in Flask

Looking for some guidance on creating an HTML form with two input fields. Check out the HTML template code below: <form role="form" action="/cities/" method="get" autocomplete="on"> <label for="#input1"><strong>Country:</strong&g ...

Is it possible in Vue.js to create a reactive functionality for a button using a watcher for "v-if" condition?

I have a userlist page with various profiles, including my own. A button is supposed to appear only when viewing my own profile. The issue arises when switching from a different profile to my own (changing the router parameter) - the button should show up ...

Changing the event handler of a jQueryUI accordion dynamically from "click" to "mouseover" as needed

I am facing a scenario where I need to drag an item from a list and drop it into a target within an accordion. The challenge is that the target may be in a panel that is not currently open. To address this issue, I am looking to dynamically switch the acc ...

Using JavaScript to implement CSS3 with multiple background images

Is there a way to programmatically define multiple background images in CSS3 using JavaScript? While the common approach would be: var element = document.createElement( 'div' ); element.style.backgroundImage = "url('a.png') 0 100%, ur ...

What is the best way to retrieve a value from a function that contains multiple nested functions in Javascript?

The issue at hand is my struggle to extract a value from a nested method and utilize it outside of its parent method. I am aiming for the output of "console.log(someObjects[i].valueChecker);" to display either "true" or "false," but instead, it simply retu ...

What is the method for displaying html files in a POST request?

This is the code snippet I am working with: app.post('/convert', function(req,res){ var auxiliar = "somo Ubuntu command line(this works)"; exec(auxiliar, function(err, stdout, stderr){ if(err){ console.log ...

showing javascript strings on separate lines

I need assistance with displaying an array value in a frontend Angular application. How can I insert spaces between strings and show them on two separate lines? x: any = [] x[{info: "test" + ',' + "tested"}] // Instead of showing test , teste ...

"Comparison: Java Installation vs. Enabling Java in Your Web Browser

Is there a method to determine if Java is currently running on your system or if it has been disabled in your browser? Our application relies on Java applets, and we typically use "deployJava.js" to load the applet. However, even when Java is disabled in t ...

Alter the Vue view using an object instead of the url router

Currently working on a chrome extension using Vue.js where I need to dynamically update views based on user interactions. Usually, I would rely on the Vue Router to handle this seamlessly... however, the router is tied to the URL which poses limitations. ...

Problem identified with Vue.js: The Log in screen briefly flashes before redirecting the authenticated user (resulting in a full page refresh)

My routing is functioning properly, utilizing navigation guards to prevent users from accessing the login or register routes once they are signed in. However, when I manually type '/auth/signin' in the address bar, the login screen briefly appear ...

Utilizing $.getJSON to initiate a selection change event

I'm currently working on implementing a feature that involves adding categories to a dropdown list using jQuery Ajax. The goal is to load subcategories when a particular option is selected. However, I've encountered an issue where the addition o ...

Is there a quicker method than using document.getElementById('element-id').innerHTML to retrieve content?

Currently, I am developing a user-friendly step-by-step wizard for my website to gather information about custom orders. Utilizing JavaScript, I have been tasked with updating the content of each "page" using the document.getElementById('element-id&ap ...

Ways to update a div periodically with new data fetched from a file - Here's How!

I am looking to auto-refresh a specific div every few seconds on my index.php page below. <?php session_start(); if (! check_write()) { redirect('testlogin.php'); return; } if (file_exists('lmt.json')) { $lmt = json_de ...

Making AngularJS 'PUT' requests: The process of submitting only the data in a form

I am facing an issue while updating user data in Angular. When I send a 'PUT' request, the entire user $scope is being sent instead of only the fields visible on the form. To retrieve and update the data, I am using a Factory. Below is my edit f ...

Using JQUERY to create a dropdown menu that dynamically changes based on the date field

I am currently working on a JQUERY project and facing a challenging situation. I usually know how to create dropdown menus that depend on one another, but this time I need a dropdown menu that displays age ranges based on the date entered in the birth-date ...

When utilizing the React API Fetch, there may be instances where not all data is returned. However

Having some trouble with my FetchData class. I am receiving a list of data, but it's in an array format. When I try to access specific values like countries: data.Countries[0], I can get individual values based on the index. However, what I really wan ...

`Assembling HTMX with Tailwind Css and Shadcn UI: A Comprehensive Guide`

After discovering HTMX's capabilities to potentially replace JavaScript on the client side, I am eager to transform my NextJs (ReactJs) project. How can I seamlessly convert my existing project into an HTMX-based setup while retaining Tailwind and Sha ...

Audio suddenly no longer working after transferring project to React

View my reproducible example here. This is a demonstration of the issue I am facing. Previously, when the page consisted only of static html with javascript, the sounds were functioning correctly. However, after refactoring into a React app, the sounds ha ...

Issues with loading an external CSS file in an HTML document

I've been attempting to implement a loading animation using jQuery, but I'm encountering issues with loading the CSS file. I have tried various paths for the css file such as: <link href="css/animation.css" type="text/css" rel="stylesheet"> ...