How to Import SVGs into your Next.js Project?

In this article, let's see how we can import SVGs into a Next.js project.

How to Import SVGs into your Next.js Project?

Table of Contents


Next.js is my go-to framework for building any type of frontend application. It has many things pre-configured right out of the box. For example, you have built-in support for CSS, CSS modules, sass, etc. It also comes with built-in support for environment variables and many other things. But one thing you cannot do directly in Next.js is to import SVG files in your components. In this article, I will explain the steps with which you can set up your Next.js project so that it can support importing SVG files into your components.
I have created a basic Hello World NextJs app. See the file structure below.
notion image
We are going to use a babel plugin called babel-plugin-inline-react-svg.
npm install --save-dev babel-plugin-inline-react-svg
Now, lets add that plugin to our .babelrc file.
Create a file named .babelrc at the root of your project if it is not already present and add the following contents to it.
{
  "presets": ["next/babel"],
  "plugins": ["inline-react-svg"]
}
That is all we need to enable svgs in out Next.js project.
Let’s test and see if it works. Let’s import Next.js logo into our index page
// src/pages/index.js
import NextLogo from '../assets/nextjs.svg'

export default function Home() {  
	return (
		<div>
			<NextLogo width={100} height={100} fill={'red'} />
			<h1>Hello Next.js</h1>    
		</div>  
	)
}
Now, run the development server with next dev.
notion image
You can see here that NextJs logo is imported and rendered successfully.
There are many other ways to import SVGs into your Next.js project. But I feel like this is the easiest way to do so.

Note:

If all you want is to import SVG files into your component as an image, and you don’t want to add any SVG specific properties like fill to it, then you can simply move the file to /public folder of your Next.Js project and then use an img tag to render SVG.
<!-- nextjs.svg image is at public/nextjs.svg -->
<!-- NextJs automatically serves files like images that are under 'public' folder -->
<img src='/nextjs.svg' />
All the code that is written in this article is available on my GitHub at pbteja1998/nextjs-with-svg
 
Bhanu Teja P

Written by

Bhanu Teja P

24yo developer and blogger. I quit my software dev job to make it as an independent maker. I write about bootsrapping Feather.