DEV Community

Yariv Shamash
Yariv Shamash

Posted on

4 2

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!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up