DEV Community

Yariv Shamash
Yariv Shamash

Posted on

Next.js and <svg />

A quick share of my experiance with Next.js and .svg files.

I needed to display a bunch of .svg files on a Next.js app.

Using .svg files with Next.js super cool <Image /> component is not recommended since it can create unexpected behavior and lead to vulnerabilities if a security policy header is not defined.

So I needed to incorporate a loader.
The quickest way I found was using .babelrc file and babel-plugin-inline-react-svg.
It worked! well kind of.. πŸ˜• Some graphics were not displayed and some did, while others were cut off unexpectedly.

I dug a bit more and found this answer by @felixmosh on stackoverflow using next.config.js file.

TL;DR:

~ Step One:

$ npm install --save-dev @svgr/webpack
Enter fullscreen mode Exit fullscreen mode

~ Step Two:

// next.config.js

module.exports = {
  webpack(config) {
    config.module.rules.push({
      test: /\.svg$/,
      issuer: {
        test: /\.(js|ts)x?$/,
       // for webpack 5 use
       // { and: [/\.(js|ts)x?$/] }
      },

      use: ['@svgr/webpack'],
    });

    return config;
  },
};
Enter fullscreen mode Exit fullscreen mode

If you used the above solution make sure to give the question and the answer a vote up on stackoverflow πŸ™‚


Side note, if you’re using typescript in your project and feel bad that the next.config file is a .js file don’t because next does not plan β€œto transpile next.config.js.” As you can see in this issue.

I hope it helped, thanks for reading!

Top comments (0)