How to apply styles to the HTML in Next.js at server side render?

5k Views Asked by At

Visit Next.js and notice the page request in the network tab. Preview shows not just the HTML but completely pre-styled page.

enter image description here

When we use Styled-Components and Material-UI they have exposed ServerStyleSheet which is used for serving the required styles for the first render within the HTML.

import { ServerStyleSheet } from 'styled-components'
import { ServerStyleSheets } from '@material-ui/core/styles'

How can we achieve same output when using react-bootstrap or custom css like test.css?

4

There are 4 best solutions below

0
Ramakay On

Do you care if its a test.css or React bootstrap - Instead why not just inline all critical stylesheets?

It might be worth trying out their experimental feature

  1. Add experimental: { optimizeCss: true } to next.config.js
  2. Install [email protected] as a dependency

Via How to inline CSS in the head tag of a NextJS project?

2
Adarsh On

use Tailwind css

https://tailwindcss.com/

We can simply use classes and it make everything super easy for you design

0
Neezar On

Add your style file on the the _app file, you can create this file inside the pages directory in nextjs

import { AppProps } from "next/app";
import 'bootstrap/dist/css/bootstrap.min.css';
import "../your_style.css";

function App({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />;
}


export default App;

for react-bootstrap , you need to add npm i react-bootstrap bootstrap

0
Aayush On

Nextjs allows you to display SSG/SSR pages and javascript-disabled users will still be able to see your app but the layout will be messy if you use react-bootstrap components to build your layout.

To use react-bootstrap at SSR:

  1. Install :

    npm i react-bootstrap bootstrap
    
  2. Import bootstrap styles in your _app.js:

    import 'bootstrap/dist/css/bootstrap.min.css';
    
  3. You can then use your react-bootstrap components as you would do in reactjs:

import {Container, Row, Col} from 'react-bootstrap';
        
const Layout = () => (
  <>
    <Container fluid>
      <Row>
        <Col>
          <p>Running on Next.js at SSR</p>
        </Col>
      </Row>
    </Container>
  </>
);
        
export default Layout;