Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nextjs assets 404 Not Found when using dynamic rouitng while ssr

I had a static folder with an older version of nextjs. I updated my nextjs to use public folder.

"next": "^9.4.0",
"react": "^16.13.1",
"react-dom": "^16.13.1",

this is my nextjs config:

const withPlugins = require('next-compose-plugins');
const withCss = require('@zeit/next-css');
const withSass = require('@zeit/next-sass');
const withImages = require('next-images');
require('dotenv').config();
const withSourceMaps = require('@zeit/next-source-maps')();

if (typeof require !== 'undefined') {
  // eslint-disable-next-line no-unused-vars
  require.extensions['.css'] = file => {};
}

const nextConfig = {
  env: {
    BUILD_ENV: process.env.BUILD_ENV,
  },
  webpack: (config, { isServer }) => {
    if (!isServer) {
      // eslint-disable-next-line no-param-reassign
      config.resolve.alias['@sentry/node'] = '@sentry/browser';
    }

    if (isServer) {
      const antStyles = /antd\/.*?\/style\/css.*?/;
      const origExternals = [...config.externals];
      config.externals = [ // eslint-disable-line
        (context, request, callback) => { // eslint-disable-line
          if (request.match(antStyles)) return callback();
          if (typeof origExternals[0] === 'function') {
            origExternals[0](context, request, callback);
          } else {
            callback();
          }
        },
        ...(typeof origExternals[0] === 'function' ? [] : origExternals),
      ];

      config.module.rules.unshift({
        test: antStyles,
        use: 'null-loader',
      });
    }
    return config;
  },
};

module.exports = withPlugins(
  [
    [withImages],
    [withCss],
    [
      withSass,
      {
        cssModules: true,
        cssLoaderOptions: {
          localIdentName: '[path]___[local]___[hash:base64:5]',
        },
      },
    ],
    [withSourceMaps],
  ],
  nextConfig,
);

When I refresh the page all my styles are like this:

enter image description here

I have a dynamic page called [cat], so all the paths are like:

http://localhost:3030/cat/static/css/antd.min.css

Do you know how can I fix this?

When I route with Link everything is ok but when I refresh the page the assets are not found because of the dynamic route!

this is the directory:

enter image description here

like image 236
Afsanefda Avatar asked May 18 '20 08:05

Afsanefda


People also ask

How do I navigate to a dynamic route in next JS?

Dynamic routes can be extended to catch all paths by adding three dots ( ... ) inside the brackets. For example: pages/post/[...slug].js matches /post/a , but also /post/a/b , /post/a/b/c and so on.

How do I redirect a 404 page in next JS?

To create a custom 404 page you can create a pages/404. js file. This file is statically generated at build time. Note: You can use getStaticProps inside this page if you need to fetch data at build time.

Is next JS good for dynamic websites?

Next JS is perfect for that because websites and applications created with Next JS are superfast. And you should already know that page load speed is one of the key SEO ranking factors. In other words, the faster the page is the bigger chances of ranking higher than slower sites.

Which method is used in Nextjs for statically generating dynamic routes?

The companion life-cycle method getStaticPaths of getStaticProps lets us use the data we have at build-time to specify which dynamic routes (like /pages/blog/[slug] ) we want to generate statically.


1 Answers

I had a similar issue where I was using Next.js Dynamic Routes to capture the URL path param but the CSS and JS assets would not load because it was prepending the path onto my Layout assets. i.e. in your sample, it would add cat in front of my asset's resource file path. My pages look something similar to: pages/cats/[something].js

I fixed this by adding a '/' to the resource path

Try correcting your Head/Layout

from:

<link rel="stylesheet" href="static/css/antd.min.css" />

to:

<link rel="stylesheet" href="/static/css/antd.min.css" />

This fixed my CSS and JS issues with displaying and pulling from the correct resource path link.

like image 123
Kelvin Avatar answered Oct 04 '22 04:10

Kelvin