Can't import SVG into Next.js

You need to provide a webpack loader that will handle SVG imports, one of the famous one is svgr.

In order to configure it to work with next, you need to add to your next.config.js file the usage of the loader, like that:

// next.config.js

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

    return config;
  },
};

For more config info, check out the docs.

Don't forget to install it first: npm install@svgr/webpack

Edit

I've added issuer section which strict these svg as component only for svgs that are imported from js / ts files. This Allows you to configure other behaviour for svgs that are imported from other file types (such as .css)


Install next-images.

yarn add -D next-images

Create a next.config.js in your project

// next.config.js
const withImages = require('next-images')
module.exports = withImages()

I personally prefer next-react-svg plugin which allows to treat SVG images as React components and automatically inline them, similar to what Create React App does.

Here is how to use it:

  1. Install next-react-svg:
npm i next-react-svg
  1. Add necessary settings to next.config.js:
const withReactSvg = require('next-react-svg')
const path = require('path')

module.exports = withReactSvg({
  include: path.resolve(__dirname, 'src/assets/svg'),
  webpack(config, options) {
    return config
  }
})

The include parameter is compulsory and it points to your SVG image folder.

If you already have any plugins enabled for your Next.js, consider using next-compose-plugins to properly combine them.

  1. Import your SVGs as ordinary React components:
import Logo from 'assets/svg/Logo.svg';

export default () => (
  <Logo />
);

That's it. From now on, Next.js will be including SVG images imported this way into the rendered markup as SVG tags.