Creating optimized CSS builds for Next.js production

In dev mode, I have separate Custom CSS files for different layouts which work fine. However, when I publish my app in production mode, Nextjs combines all the CSS files together causing issues with my layouts.

Answer №1

Typically, following the build process, we move all CSS and JS chunks to a designated static folder. This enables Next Js to serve the requested page from the static folder when queried by the server (based on the request).

Server.js:

const staticDir = path.resolve(__dirname, "..", ".next/static");
server.use(compression());
server.use("/_next/static", express.static(staticDir));



    server.get("/_next/*", (req, res) => {
      /* serving _next static content using next.js handler */
      handle(req, res);
    });
    server.get("/static/*", (req, res) => {
      /* serving _next static content using next.js handler */
      handle(req, res);
    });

Add the following lines in your _document.js file and provide details of the configuration added in next.config.js.

_document.js

// Render app and page and get the context of the page with collected side effects.

  const sheets = new ServerStyleSheets();
  const originalRenderPage = ctx.renderPage;

  ctx.renderPage = () =>
    originalRenderPage({
      enhanceApp: App => props => sheets.collect(<App {...props} />)
    });

  const initialProps = await Document.getInitialProps(ctx);

  return {
    ...initialProps,
    // Styles fragment is rendered after the app and page rendering finish.
    styles: [
      ...React.Children.toArray(initialProps.styles),
      sheets.getStyleElement()
    ]
  };
};

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

Can an intercepting route be implemented in Next.js without the need for a parallel route?

According to the nextjs documentation, Intercepting Routes can be utilized alongside Parallel Routes to generate modal windows. I am curious if this functionality is exclusively for modals or if intercepting routes should always be combined with parallel r ...

Error encountered while using Material-UI ThemeProvider in an ES6 module being built with rollupJs: Invalid hook call

Currently, the issue at hand is quite straightforward. I am in the process of developing an application where I aim to divide different parts into components. To achieve this, I made a decision to establish a boilerplate for generating modules using rollup ...

Adjust the font size based on the dimensions of the container

I'm currently working on a script that dynamically sets the font-size based on the container's dimensions and the length of the text. This is what I have implemented so far. window.onload = function () { var defaultDimensions = 300; ...

Navigating after a data submission in React JS and Node JS

Trying to send data to another component page is proving to be a challenge after making a post request to my Node.js server. The first component I need to redirect from: (Unfortunately, I can't share all the code as it's quite lengthy). fetch(& ...

The CSS overflow property does not seem to be functioning properly when applied to a span element that

Here is my current setup: http://jsfiddle.net/YKXUb/1/ My CSS looks like this: .two { height: 100%; width: 100%; border:1px solid green; } .hold { float: left; height: 100%; width: 35%; border:1px solid green; } .right { hei ...

What might be the reason for the border not reaching the bottom of the popup in my chrome extension?

I am currently working on a Chrome extension and using Bootstrap 5 with Sass to style its popup. However, I have encountered an issue where the border of the popup does not extend to the bottom as expected. What could be causing this problem? popup.html & ...

The renderValue property is malfunctioning in the Material-UI native Select component

Whenever I utilize the native prop in the MUI Select component, the renderValue prop fails to function properly. Additionally, if I attempt to assign a custom value to the value prop, it does not display. Take a look at the code snippet below: const [selec ...

The Ternary Operator in React Native

Looking for a way to truncate a user's name using a ternary operator and add ... if it exceeds a certain character length. I have tried different approaches but always end up with this code snippet, here is the initial code and my current attempt. < ...

Having difficulty troubleshooting the /app router application on version 13.4.x

Having trouble debugging a server-side process in my Next.js app that uses the /app router. To reproduce the issue, simply create a new Next.js app with npx create-next-app and select the app router option. I've attempted to attach a debugger to the ...

Error encountered while utilizing MUI Button: Unable to access property 'borderRadius' from an undefined source

import React, { Component } from 'react'; import './App.css'; import Screen from './components/Screen/Screen'; import Button from './components/Button/Button'; import { MuiThemeProvider, createMuiTheme } from 'm ...

How can I create a pop-up notification using React that only appears once right after the user logs in for the first time?

I have implemented react-toastify for displaying popup messages. After logging in, when the page redirects to profile.js, I included a useEffect hook that runs on mount to display a notification. useEffect(() => { notify(); }, []); const notify ...

Issues arise with transferring React component between different projects

My goal is to develop a React component that serves as a navigation bar. This particular component is intended to be imported from a separate file into my App.js. Currently, the component is designed to simply display a 'Hello world' paragraph, ...

NextJS - Accessing local files with readdir and readFile functions leads to error: Module not found when trying to resolve 'fs' module

I have been working with NextJS and have successfully used the getStaticProps functionality in previous projects to populate data. However, I recently set up a new NextJS project and it seems that this functionality is no longer working. When starting th ...

What is the best way to conceal the main list but still show the nested list within?

I'm looking for a way to conceal the main parent of a sub-list while still displaying the nested list. Furthermore, I need to ensure that the parent element doesn't occupy any space on the page when hidden. HTML <ul> <li class="par ...

Using React 360 to render components to a specific location

I have a situation in my boilerplate where I need to mount one component only when a specific method is called from another component. Any ideas on how I could achieve this? Below is the code snippet of my boilerplate: import {ReactInstance} from ' ...

Conceal the initial modal beneath the overlay when the second modal is activated

I have a situation where I am using a modal that contains a button to trigger a second modal. The issue is that the overlay of the second modal does not hide the first modal, it simply darkens the background. How can I make the overlay of the second modal ...

I am experiencing issues with the Link component in Next.js version 13.4, as it

Whenever I attempt to navigate by clicking on the buttons labeled About, Experience, and others, the page does not redirect me accordingly. Oddly enough, if I manually input the endpoint for that specific page like http://localhost:3000/#about, it function ...

Using Jquery to attach an event to a particular div which is part of a group of divs sharing

I am trying to implement a mouseup event on a series of divs that, when clicked, will reveal a child div ('menu'). All the parent divs have the same class. Here is an example: <div class="container"> <div class="menu"><p>Text ...

vue-router: error encountered while attempting to load asynchronous component for rendering

I'm new to vue-router and having trouble getting it to work. When I try to start my app, these errors pop up: [vue-router] Failed to resolve async component render: TypeError: _vm is undefined 49:16:39 [vue-router] uncaught error during route navigat ...

Implement a hover effect on a specific class targeting a nested element using JavaScript

Is there a method to apply a class that modifies rules for a child element using Javascript? I have successfully added it with CSS but am struggling to do the same with Javascript. Removing the class in JS is easy by referencing the classname before the ho ...