Next.js 13 Hydration: Bundling error with canvas dependency in react-pdf solved

Server Side Rendering (SSR) widens the frontend possibilities of frameworks enormously, but on the other hand makes debugging for the webdev more difficult.

Tuedo#012

 by  tuedodev

28
Dec 2022
 0

If you like me have recently tried out the brand new Next 13 release in the beta version, you sometimes run into Webpack problems with modules for components that cannot be pre-hydrated on the serverside because they make exhaustive use of the browser API. I experienced this with the canvas module, which is used by the excellent PDF package react-pdf.

Since Next 13 breaks the old pattern of getServerSiteProps and getStaticSiteProps with the server and client side distinction for the hydration, all components that have to fall back on browser-specific routines and functions have to be marked with the label 'use client'.

Nevertheless, webpack continued to cause error messages, a quick solution to the problem could not be found, especially since Next 13 has only been beta for a few weeks in a more stable version.

It was only a note from hfossli-agens that brought the solution. A small insertion in the next.config.js configuration file deactivated the unnecessary serverside bundling of the canvas dependency inside the react-pdf module:

/** @type {import('next').NextConfig} */
const nextConfig = {
	// add this to the next.config.js file
	webpack: (config) => {
		config.resolve.alias.canvas = false;
		config.resolve.alias.encoding = false;
		return config;
	},
};

module.exports = nextConfig;

To be on the safe side, you should not only restart the server after this change to the configuration file, but also delete the entire .next folder in the web app so that your bundler do not resort to an old caching and create further error messages.

This post has not been commented on yet.

Add a comment