Working with SVGs in Next.js has multiple approaches depending on your use case. Let’s go through the most common and recommended methods.
1️⃣ Inline SVG
Use case: good for small SVGs that are not reused anywhere in your app.
export default function InlineSvgExample() {
return (
<button className="flex items-center gap-1 px-2 py-1 bg-gray-100 rounded">
{/* Inline SVG icon */}
<svg className="w-3 h-3" fill="currentColor" viewBox="0 0 16 16">
<path d="M8 0a8 8 0 1 0 8 8A8 8 0 0 0 8 0zm0 15A7 7 0 1 1 15 8 7 7 0 0 1 8 15z" />
</svg>
Add
</button>
);
}
Pros:
- No extra configuration needed.
Cons:
- Poor maintainability if reused in multiple places.
- Harder to manage styles dynamically.
2️⃣ Place SVG in the /public Folder and Display with Image Component
Best choice when: you don’t need to set svg style except for width and height.
import Image from "next/image";
<Image src="/github.svg" width={24} height={24} alt="Github" />
Pros:
- Simple and straightforward.
- Leverages Next.js built-in
Imageoptimization.
Cons:
- Limited styling options.
- Cannot dynamically change colors or other attributes via React props.
3️⃣ Import SVG as a React Component
Best choice when: you want to style the SVG with CSS or Tailwind, or to change colors dynamically.
Setup:
1. Place your SVG file in /src/assets or /assets.
2. Install @svgr/webpack if you haven’t already:
npm install -D @svgr/webpack
3. Adjust next.config.ts to configure loader:
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
reactCompiler: true,
turbopack: {
rules: {
'*.svg': {
loaders: ['@svgr/webpack'],
as: '*.js',
},
},
},
};
export default nextConfig;
For more loader configurations, check: Configuring webpack loaders.
Then import svg as a React Component:
import GithubIcon from "@/assets/icons/GithubIcon.svg";
<GithubIcon className="w-6 h-6 text-gray-500" />
Pros:
- Full styling control with Tailwind or CSS.
- Dynamic props for size, colors, className, etc.
- Perfect for reusable icons/components.
Cons:
- Slightly more setup.
✅ Conclusion:
- Use inline SVG for one-off small icons.
- Use
/public+Imagefor static SVGs with no dynamic styling. - Use SVG as React component for reusable, styled, and dynamic icons.
Top comments (1)
Thank you, Marina, for this practical and up-to-date guide.
Your clear breakdown of SVG import methods in Next.js makes development simpler without unnecessary complexity. I truly appreciate the time and effort you put into sharing such valuable insights with the community.
Wishing you continued success, growth, and many moments of happiness on your journey. Keep inspiring us!
🤍🧊🗻🌳