How can I use next js with ant design library properly with server side rendering?

1.2k views Asked by At

I cloned the the official next js example with ant design link : https://github.com/vercel/next.js/tree/canary/examples/with-ant-design

Then I did npm install to install all dependencies . Then I did npm run dev to see everything is working fine . Then I did npm run build to build the next js app and then I run npm run start to run the built app in localhost .

The problem is when I go to network tab and select localhost page and then preview it from the preview tab , the ant design is not actually applying with server side rendering and I see no styles at all . It takes half second for ant design css to apply which is not what I want .

How can I use ant design with next js server side rendering properly ?

1

There are 1 answers

0
Olavi On BEST ANSWER

What you might be looking for is inlining the CSS, in order for the browser to apply them more quickly without needing to fetch the CSS resources as separate requests first.

There's a question about official support for this, but no answer yet: https://github.com/vercel/next-plugins/issues/364

However, there's a workaround, that can be found in https://github.com/vercel/next-plugins/issues/238 and I tried this and it works.

To achieve inlining the CSS, add a file called _document.js in the pages folder, with the following contents:

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

class CustomNextHead extends Head {
  // TODO: This might not be needed if Next.js implements built-in support
  // https://github.com/zeit/next-plugins/issues/364
  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>
    );
  }
}