javascriptwebpacknext.jsnext.js13file-loader

How to load pdf files in nextjs using webpack file-loader (404 Error)


In my nextjs app, I want to add a button which user clicks on it and a pdf file downloads. I added the pdf file to public/documents/ and imported it and added it to link href. But after clicking it, it shows a 404 page even the generated file is exist and i can watch it on Chrome inspect > sources (in _next). I am using webpack file-loader.

Next config:

const nextConfig = {
  output: "standalone",
  webpack: (config, options) => {
    config.module.rules.push({
      test: /\.(png|gif|mp4|pdf)$/i,
      use: [
        {
          loader: "file-loader",
          options: {
            name: "[name].[ext]",
          },
        },
      ],
    });
    return config;
  },
};

My page code:

import LeaderInstructions from "@documents/leaders-instructions.pdf";

...
//other codes
...

<a
      href={LeaderInstructions}
      target="_blank"
>

Anyone knows what should I do?


Solution

  • Thanks to @Vayne Valerius. I updated to webpack 5 method and works now! Config code:

    const nextConfig = {
      output: "standalone",
      webpack: (config, options) => {
        config.module.rules.push({
          test: /\.(pdf)$/,
          type: "asset/resource",
        });
        return config;
      },
    };