Using a package with `webfontloader` in NextJs for Server-Side Rendering: A guide

Currently, I am working on creating an application with nextJS and incorporating a package that utilizes Webfontloader internally. After installing the library, my application encountered an error preventing it from running successfully. It seems like the error occurred when nextjs attempted to compile an app referencing window on the server-side. Any assistance in resolving this issue would be greatly appreciated.

ReferenceError: window is not defined
  at eval (webpack-internal:///./src/[REDACTED]/node_modules/webfontloader/webfontloader.js:1:711)
  at eval (webpack-internal:///./src/[REDACTED]/node_modules/webfontloader/webfontloader.js:18:103)
  at Object../src/[REDACTED]/node_modules/webfontloader/webfontloader.js (/Users/MyUser/codebase/codepan/[REDACTED]/.next/server/pages/index.js:2941:1)
  at __webpack_require__ (/Users/MyUser/codebase/codepan/[REDACTED]/.next/server/webpack-runtime.js:33:43)
  at eval (webpack-internal:///./src/[REDACTED]/lib/Button/ButtonGroup.js:39:22)
  at Object../src/[REDACTED]/lib/Button/ButtonGroup.js (/Users/MyUser/codebase/codepan/[REDACTED]/.next/server/pages/index.js:982:1)
  at __webpack_require__ (/Users/MyUser/codebase/codepan/[REDACTED]/.next/server/webpack-runtime.js:33:43)
  at eval (webpack-internal:///./src/[REDACTED]/lib/Button/index.js:16:20)
  at Object../src/[REDACTED]/lib/Button/index.js (/Users/MyUser/codebase/codepan/[REDACTED]/.next/server/pages/index.js:1015:1)
  at __webpack_require__ (/Users/MyUser/codebase/codepan/[REDACTED]/.next/server/webpack-runtime.js:33:43)

Answer №1

If you want to dynamically load this library on the client side only, you can do so with the following code:

const checkIfServer = () => typeof window === 'undefined'

if (!checkIfServer()) {
        import('hammerjs').then(imported => {...})     
})

Another option is to explore using dynamic imports without server-side rendering in next.js:

https://nextjs.org/docs/advanced-features/dynamic-import

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

I'm having trouble executing the straightforward code I discovered on GitHub

https://github.com/Valish/sherdog-api Upon downloading the sherdog-api, I embarked on installing node.js as a prerequisite for using this new tool, despite having no prior experience with such software. Following that, I opened up the command prompt and n ...

The specified parent tag for the 'img' tag is 'span', however it should be 'i-amphtml-sizer-intrinsic'. Custom JavaScript is not permitted in this case

Issue: The parent tag of the 'img' tag is 'span', but it should be 'i-amphtml-sizer-intrinsic'. Custom JavaScript is prohibited. More information here Error occurred while running async build (/home/vrch/Desktop/vrch-next/nod ...

Managing the position of the caret within a content-editable div

I need help with editing a contenteditable div in HTML <div contenteditable="true" id="TextOnlyPage"></div> Here is my jQuery code: var rxp = new RegExp("(([0-9]+\.?[0-9]+)|([0-9]+))", "gm"); $('#TextOnlyPage').keyup(function( ...

Enzyme fails to locate text within a div even though it is present

In my current test scenario, I have a set of data displayed in Material-UI Cards. The data is provided through a JSON array consisting of objects with fields like projectName, crc, dateCreated, createdBy, and lastModified. { projectName: 'P ...

Creating a module within a component in angular - step by step guide

I am interested in dynamically creating a component inside another component. This will allow me to pass my dynamic HTML template directly to the decorator like this: //code /** * @param template is the HTML template * @param container is @ViewChild(& ...

Issue with Angular cookies not being able to remove the cookie within a Chrome extension

I am currently developing a Chrome extension that includes login and logout features. After a successful login, the server sends a token that I need to store in a cookie. The process looks like this: function success(response) { if(response.data & ...

Tips for arranging Intervals in sequence?

I've been developing a customized Pomodoro timer with user-defined work and rest times. In my Timer component, I have the following initial logic: useEffect(() => { start(3); start(timeData.workTime); start(timeData.restTime); }, []) c ...

Chrome fails to select item in Protractor test, while Safari succeeds

While my test passes smoothly on Safari, I encountered an issue on Chrome where the following code snippet fails to work: it('should click the first source and get to the source preview page', function () { var grid_icon = element(by.css(&a ...

Missing data list entries for next js server actions

After successfully running my add function, I noticed that the data I added earlier is not being reflected in the list when I check. import React, { useEffect, useState } from "react"; import { createPost } from "./actions"; import { SubmitButton } from ". ...

The resource in CosmosDB cannot be found

I have successfully stored documents on Cosmos, but I am encountering an issue when trying to retrieve them using the "read" method. this.cosmos = new CosmosClient({ endpoint: '' key: '' }); this.partitionKey = '/id' thi ...

Encountering an issue in Next.js where the state of one component cannot be sent to another due to the error message: "Uncaught TypeError: setSelectedTag is not a function at

I recently utilized the useState hook to create a state in my project. I encountered an issue when attempting to pass the setState function as a prop to a child component. Upon using this function in a button's 'onclick' event, an error surf ...

Organize an array based on its ratio

I am attempting to organize an array based on the win and lose ratio of each player. This is how my code currently looks: const array = [{playerName: 'toto', win: 2, lose: 2}, {playerName: 'titi', win: 0, lose: 0}, {playerName: &apo ...

Removing a property from a JSON object when initiating an Ajax request in JavaScript

Looking for guidance on JavaScript and ajax as a beginner. I have a JSON with an output cell that I want to remove: { "cells": [{ "metadata": { "trusted": true, "collapsed": false }, ...

Looking to incorporate new values without replacing them in react.js and mongoDB

function getFilterQuery() { const completedWorkState = WorkflowStates.findOne({title: 'Completed'}); const inProgressWorkState = WorkflowStates.findOne({title: 'In Progress'}); const identifiedWorkState = WorkflowStates.findOne ...

How can I implement a jQuery modal dialog that loads a form page with pre-existing jQuery code for Autocomplete functionality?

I am facing an issue where I have a dynamically generated form on a web page and I want to display it using the jQuery UI modal dialog. Previously, I was suggested a solution that worked when my form did not already contain jQuery UI components like Autoc ...

Choose according to reactjs using react-select

Currently working on a ReactJS app that includes a page with two select elements, where one is dependent on the other. I am integrating react-select and @material-ui. Within the context of dates: [ { "id": 1, "name": "20 ...

AngularJS nested menu functionality not functioning properly

I am currently working on a nested menu item feature in AngularJS. I have a specific menu structure that I want to achieve: menu 1 -submenu1 -submenu2 menu 2 -submenu1 -submenu2 angular.module('myapp', ['ui.bootstrap']) .cont ...

Combining objects in JavaScript

I am currently working on converting the object received from the server into a format compatible with the backend system. I have a received object that looks like this { 'User.permissions.user.view.dashboard': true, 'Admin.permissio ...

Having trouble with the pagination feature while filtering the list on the vue-paginate node

In my current project, I have integrated pagination using the vue-paginate node. Additionally, I have also implemented filtering functionality using vue-pagination, which is working seamlessly. Everything works as expected when I enter a search term that d ...

Unbinding or undoing an 'onclick' event when another 'onclick' event is triggered

I am facing an issue where clicking on elements with 'onclick' functions works as expected, but when I click on a different element with another 'onclick' function, the first one remains active. What I actually want is for the previous ...