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

Caching files with service worker in React app

Currently working on my very first React app created with create-react-app. While the production build already includes a service-worker.js, I need to manually add a couple of JavaScript worker files that are not being cached by the service worker as of no ...

Error encountered while attempting to import the mongoose npm module into a React application

I'm encountering an issue in my React project where I am trying to include an npm module within a component. Here's an example: var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test', {useNewUrlParser ...

Changes in the amount field in PayPal React results in the appearance of additional buttons on

Eliminating react-paypal-button-v2 ~~~ results in a 60KB reduction in overhead For a related query, check out this post which recommends the use of react-paypal-button-v2 I endeavor to create a React PayPal button that dynamically adjusts the billing amo ...

What is the best way to alter the background-color of an element that is contained within a GatsbyJS component, depending on the specific page where the component is being utilized?

As a first-time GatsbyJS website builder, I am working on creating reusable components for my site. One of these components is the footer, and I have already structured it. Now, I have a dilemma - I want to change the color of a specific <div> within ...

How can I properly save a PNG image with alpha transparency to be compatible with IE6?

Seeking advice on saving a visually pleasing 1 or 8-bit PNG image that renders well in IE6. Open to suggestions on alternative methods as I have experience with Fireworks but exploring new options. Thank you in advance! ...

Tips for positioning a div to the left once the minimum width has been reached?

<div id="container"> <div id="subsSection"> <div class="leftSection">ss</div> <div class="rightSection">ss</div> </div> </div> (1) My goal is to have the subsection div centered on the ...

What is the process for embedding images and text within a nested division element?

I have a website layout with 4 main sections: header, left side, right side, and footer. I would like to further divide the header into two sections - left header and right header. The right header should contain an image along with other options like home ...

Failure occurred in sending POST request from React app to the Rocket backend causing an error

I am currently developing a web application using Rocket for the backend and React for the frontend. Below is the code snippet for the login page: #[post("/login", data = "<data>")] pub fn login( conn: DbConn, mut cookies: Cookies<'_ ...

Elevate - Adjust state based on actionable tasks

I am striving to establish a specific data flow for my project: Determine the record-id from react-router Assign this id as a state property Once this property is set, all relevant components with their own reducer and actions should retrieve data base ...

Rendering ReactJs on the server side versus the client side

I'm utilizing react-router for managing both server-side rendering and client-side rendering in my React application. However, I've noticed that the entry point of my app contains the following code: Router.run(routes, Router.HistoryLocat ...

Struggling with updating the background color of multiple HTML elements with the same class in real-time

I'm facing an issue with dynamically updating background colors of specific elements using ajax, JSP, and a servlet call. Even though all the lines of code seem to be executing, there is no visible change on the front end. I've attached my JS fun ...

Can you answer this straightforward query about CSS positioning?

I am currently facing a challenge in creating a small div (header class) that overlays a main banner image div (banner class). When I maximize my browser window, the positioning is correct. However, upon resizing the browser, the header div maintains its m ...

An empty constant object can trigger an endless cycle of re-rendering

Consider this simplified scenario: export function myCustomHook<TData = Record<string,string>> (data?: TData) { const [output, setOutput] = useState<number>(); const customFunction(data?: TData) { //In a real scenario : p ...

Using External APIs in React: A Guide

Recently, I created a React app using the npm module 'create-react-app' I ran into an issue where I needed to call an external API from api.example.com, but found that Axios was making requests to localhost instead of the external API. Here is ...

Is it possible to use mapDispatchToProps in Redux without mapStateToProps?

As I dissect Redux' todo example to gain a deeper understanding, I came across the concept of mapDispatchToProps. This feature allows you to map dispatch actions as props, which led me to consider rewriting addTodo.js by incorporating mapDispatchToPro ...

Using a condition within the map() function in React

I'm facing an issue with a map() function in my code where I need to display views based on a condition. After referring to the React documentation for writing conditions, I learned that it can be done like this: {if (loggedIn) ? ( // Hello! ) : ( ...

What is the process for creating two columns with an input box beneath them?

I am facing a challenge with my code. I am struggling to create the desired design where there are two columns and below them an input box that will be displayed when a button is pressed. The design I am aiming for can be viewed here: enter image descripti ...

Can the data of the current page be retrieved after reordering in Material-Table?

Is it possible to retrieve the current page data even after sorting? I am able to get the current page data after pagination changes, but not after sorting. The onOrderChange function only returns the column id and direction. Is there a way to get the sor ...

Aligning a child div within a parent div using HTML/CSS where the child div takes up 30% of the parent div and

Can anyone help me figure out why these two INPUT elements aren't aligning next to each other? I appreciate any assistance you can offer! <STYLE> html, body { width: 100%; height: 100%; margin: 0px; padding: 0px; } </STYLE& ...

The CSS background-image and background-color do not load on IE8

I have a specific style applied to a link: #block-menu-menu-top-menu a.contact-us-link { background-image: url("../images/top-menu-contact.png") no-repeat; background-color: none; height: 28px; text-indent: -9999px; width: 34px; } However, when ...