skip to Main Content

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?

3

Answers


  1. Chosen as BEST ANSWER

    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;
      },
    };
    

  2. Instead of importing the PDF directly, you can try referencing it using its relative path from the public directory.

    <a
      href="/documents/leaders-instructions.pdf"
      target="_blank"
    >
      Download Leader Instructions PDF
    </a>
    

    If you want to keep using the imported PDF, you can try something like this:

    import { useRouter } from 'next/router';
    
    const router = useRouter();
    
    const downloadPDF = () => {
      router.push('/documents/leaders-instructions.pdf');
    }
    
    <button onClick={downloadPDF}>Download PDF</button>
    
    Login or Signup to reply.
  3. Check the file permissions. Does your app have permission to access the file? Also, check your filename for spaces at the end. You may need to use trim to remove extraneous characters.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search