Encountering 'canvas.node' Issue While Setting up react-pdf-viewer with Next.js and TypeScript

I am having trouble integrating the "react-pdf-viewer" package into my Next.js project using TypeScript. I have downloaded the package via npm and followed the instructions in the documentation. However, when I try to compile my project, I encounter the following error:

Failed to compile
./node_modules/canvas/build/Release/canvas.node
Module parse failed: Unexpected character '�' (1:2)
You may need an appropriate loader to handle this file type.
Currently, no loaders are configured to process this file.
(Source code omitted for this binary file)
This error occurred during the build process and can only be dismissed by fixing the error.

Can anyone suggest a solution to resolve this error? Any insights on what may be causing the issue and potential fixes would be greatly appreciated.

Steps I Have Taken:

  1. I navigated to the project directory and opened the terminal.
  2. I ran the npm install react-pdf-viewer command to install the package.
  3. I followed the steps provided in the documentation to add the package to my project.
  4. Upon compiling the project, I encountered the aforementioned error.

About My Project:

  • I am using Next.js with TypeScript.
  • No issues with other packages have been observed; this problem seems isolated to the "react-pdf-viewer" package.
  • It is uncertain whether manual adjustments to the Webpack configuration are necessary.

ReaderPdf component


import React from 'react';
// Import Worker
// Import the main Viewer component
import {Viewer, Worker} from "@react-pdf-viewer/core";
// Import the styles
import "@react-pdf-viewer/core/lib/styles/index.css";
// default layout plugin
// @ts-ignore
import {defaultLayoutPlugin} from "@react-pdf-viewer/default-layout";
// Import styles of default layout plugin
import "@react-pdf-viewer/default-layout/lib/styles/index.css";


const ReaderPdf = () => {
    const defaultLayoutPluginInstance = defaultLayoutPlugin();
    const pdfFile = "/public/upload/pdf/198727.pdf";
    return (
        <>
            {pdfFile && (
                <Worker workerUrl="https://unpkg.com/@react-pdf-viewer/pdfjs-dist/build/pdf.worker.min.js">
                    <Viewer
                        fileUrl={pdfFile}
                        plugins={[defaultLayoutPluginInstance]}
                    ></Viewer>
                </Worker>
            )}
        </>
    )

};

export default ReaderPdf;

My Expectation

"I aim to effectively utilize the react-pdf-viewer package to showcase pages of a PDF file and later extract text from those pages. However, I currently lack a clear path on how to proceed with these tasks. Any sample code or step-by-step guidance from someone experienced in this regard would be highly beneficial."

Thank you in advance for any help or recommendations!

Answer №1

Don't forget to include the following code in your next.config.js

const nextConfiguration = {
webpack: (
    configuration, options
) => {
    // Remember to return the modified configuration
    configuration.module.rules.push({
        test: /\.node/,
        use: 'raw-loader',
    });
    return configuration;
}}

Make sure to install raw-loader by running npm install -D raw-loader

Additionally, add "use client" at the beginning of your component file as instructed.

This should help resolve the issue you are experiencing

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

Create a single declaration in which you can assign values to multiple const variables

As a newcomer to react/JS, I have a question that may seem basic: I need multiple variables that are determined by a system variable. These variables should remain constant for each instance. Currently, my approach is functional but it feels incorrect to ...

Issue with Jests export failure in Next.js/Firebase integration

I'm facing an issue while trying to run some Jest tests within my Next.js and Firebase project. Please bear with me if these tests are not up to par, as I am primarily using them for practice purposes. The issue: When running the test below, I encou ...

Tips for submitting a request following a change in the variable

I am in the process of developing a React application and I have implemented Auth0 for authentication. My goal is to initiate an HTTP request upon page refresh, but only if the variable isLoading is false. This way, I can access the user object once the ...

Tips for reactivating getStaticProps following an update:

For a personal project centered around an online shopping platform, I am working on managing the products page. I'm currently attempting to refresh the list of products after deleting one. My current setup involves using Next.JS in conjunction with Fi ...

TypeScript error TS6053: Unable to locate file '.ts'

I encountered the following issue: Error TS6053: Could not find file 'xxx.ts'. Oddly enough, the file compiled without any issues yesterday. However, today it seems to be causing trouble. To troubleshoot, I ran a simple test: class HelloWorl ...

When attempting to use a value outside of its block, the function may return a

My current task involves querying one collection to retrieve IDs, then using those IDs to query another collection and send back the response. The process runs smoothly until I encounter an issue with retrieving values outside of a block when using forEach ...

Displaying a disabled div depending on the dropdown selection in Angular Material

My goal is to display filters in a dropdown after they have been selected. Currently, I have static disabled divs and a dropdown where filters can be selected. This is the dropdown: <mat-form-field> <mat-label>{{ 'supplier.showFilters&a ...

Display Bootstrap Modal using Typescript in Angular

Looking for some creative ideas here... My Angular site allows users to register for events by filling out a form. They can also register themselves and other people at the same time. https://i.sstatic.net/a44I7.png The current issue ~ when a user clicks ...

"Strange Type Conversion Behavior in next.js 13: Why is res.json() Converting Numbers to Strings

I have encountered a strange issue where no matter what I do, the fetched data is being partially converted to strings. For example, the 'bialko' and 'kcal' fields are supposed to be of type Float in Prisma, yet they are getting casted ...

Tips for making a POST or GET request from a middleware file in Next.js?

I encountered a strange issue while attempting to send a GET request directly within the middleware file. Below is the code snippet from my middleware file: import { NextRequest, NextResponse } from "next/server"; export async function middlewar ...

Utilize VueJS to upload and visualize a file input on your website

I am currently working with TypeScript and Haml in conjunction with vue.js. My goal is to enable users to upload and view a file seamlessly using the vue.js framework. I have successfully managed to upload an image, however, I am facing an issue where the ...

What sets index.js apart from page.js in next.js?

https://nextjs.org/docs/pages/building-your-application/routing/pages-and-layouts While reading through the next.js documentation, I came across an interesting point. The documentation mentions that index.js serves as the root of the directory. This mean ...

Transform array sequences into their own unique sequences

Reorder Array of List to Fit My Custom Order Current Output: [ { "key": "DG Power Output", "value": "6.00", "unit": "kWh", }, { "key": "DG Run Time", "value": "5999999952", "unit": "minutes", }, { "key": "Fuel Level (Before)", "value": "8.00" ...

The specified format of `x-access-token` does not match the required type `AxiosRequestHeaders | undefined`

I am encountering an issue while trying to add an authHeader to the "Service". The error message displayed is: Type '{ 'x-access-token': any; } | { 'x-access-token'?: undefined; }' is not assignable to type 'AxiosRequest ...

Looking for a method to efficiently populate an array with values in Typescript

Here is an example of how I work with arrays in my code: var alphas: string[]; alphas = ['abc1', 'abc2', 'abc3']; // (this array can be changed) My modal class looks like this: export class Team { TeamName: string; } To ...

Mastering Light and Camera Selection in Three.js

Question, In the editor found at this link, you can click on a light or camera to select it. I am familiar with using raycaster.intersectObjects(objects) to select meshes, but how can I achieve the same result for lights and cameras which do not have mesh ...

What steps should I take to fix the issue of "[ERR_REQUIRE_ESM]: Must use import to load ES Module" while working with D3.js version 7.0.0 and Next.js version 11.0.1?

Encountered a roadblock while integrating D3 with Next.js - facing an error when using D3.js v7.0.0 with Next.js v11.0.1: [ERR_REQUIRE_ESM]: Must use import to load ES Module Tried utilizing next-transpile-modules without success Managed to make D3.js ...

I am trying to replace the buttons with a dropdown menu for changing graphs, but unfortunately my function does not seem to work with the <select> element. It works perfectly fine with buttons though

I am currently working on my html and ts code, aiming to implement a dropdown feature for switching between different graphs via the chartType function. The issue I am facing is that an error keeps popping up stating that chartType is not recognized as a ...

Accessing property values from a map in Angular

Is there a way to retrieve a property from a map and display it in a table using Angular? I keep getting [object Object] when I try to display it. Even using property.first doesn't show anything. //model export interface UserModel { room: Map ...

Mapping a TypeScript tuple into a new tuple by leveraging Array.map

I attempted to transform a TypeScript tuple into another tuple using Array.map in the following manner: const tuple1: [number, number, number] = [1, 2, 3]; const tuple2: [number, number, number] = tuple1.map(x => x * 2); console.log(tuple2); TypeScript ...