Search code examples
cssreactjsnext.jsmaterialize

Is there a way to use Materialize CDN with Next.js?


I am building a Next.js application and would like to use Materialize CDN with it. In React, I would just add the CDN links in the public/index.html file and would be good to go. Next doesn't seem to have that and I am stuck on how to do this.

I have tried with

npm install materialize-css@next --save

And I import it into the pages/_app.tsx like so:

import 'materialize-css/dist/css/materialize.min.css';
import 'materialize-css'

When it is just the first import alone, it works well, but when I import the second one to add JS, it throws me this error:

Server Error
ReferenceError: window is not defined

This error happened while generating the page. Any console logs will be displayed in the terminal window.

Also, with this kind of import, I can't make any customization to the CSS which is why I would like to use the CDN. I have been at it for days with no luck.


Solution

  • Instead of doing it in the _app.tsx do it in a _document.js file. This file is where you augment the html and body tags in NextJS projects. It's important to note that it has to be a .js file, not .tsx.

    This file is not present in your project by default and it is auto-generated by nextJS, but you can create it in the pages folder to override the default one and import the CDN there.

    You have the _document.js template and more information in the official documentation.