Returning an SVG from a Next.js Endpoint

Next.js is a powerful React framework that enables developers to create server-side rendered and statically generated web applications. One of the useful features of Next.js is its API routes, which allow you to create Endpoints as part of your application. In this article, we’ll explore how to return an SVG from a Next.js API endpoint.

Why Return SVGs from an API Endpoint?

Returning SVGs from an API endpoint can be useful in various scenarios, such as:

  • Dynamic SVG Generation: You might want to generate SVGs dynamically based on user input or other data.
  • Centralized Asset Management: Serving SVGs through an API can centralize your asset management and make it easier to update or modify them.
  • Access Control: You can add authentication and authorization to your API endpoint, controlling who can access certain SVGs.

Step-by-Step Guide

Step 1: Create a Dynamic API Route
To get started, let’s create a dynamic API route in our Next.js project. This route will handle requests for SVG files.

1. Create a new folder named [...imgPath] in the app/api/img directory. The [...path] syntax allows us to capture all segments of the URL dynamically.

2. Create a file called route.ts inside the folder previously created, with the following code:

// app/api/img/[...imgPath]/route.ts

import { promises as fs } from 'fs';
import path from 'path';

export async function GET(request: Request, { params }: { params: { imgPath: string[] } }) => {
  const svgFilePath= params.imgPath.join('/');

  try {
    const svgAbsolutePath = path.join(process.cwd(), 'public/images', svgFilePath);
    const svg = await fs.readFile(svgAbsolutePath, 'utf8');

    return new Response(svg, { headers: { "Content-Type": "image/svg+xml" } });
  } catch (error) {
    console.error('Error reading SVG file:', error);

    const svgAbsolutePath = path.join(process.cwd(), 'public/images', "fallback.svg");
    const svg = await fs.readFile(svgAbsolutePath, 'utf8');

    return new Response(svg, { headers: { "Content-Type": "image/svg+xml" } });

3. Put an SVG named “logo.svg” inside the folder /public/images/1/.

4. Put an SVG named “fallback.svg” inside the folder /public/images/.


  1. Dynamic Route: The [...imgPath] file captures all URL segments dynamically, allowing us to handle requests for SVG files located in different directories.
  2. GET Function: The GET function processes the request:
    • Extract Path: It extracts the file path from the query parameters.
    • Construct Path: Constructs the absolute path to the SVG file.
    • Read File: Uses fs.readFile to read the SVG file from the filesystem.
    • Set Content-Type: Sets the Content-Type header to image/svg+xml to indicate that the response contains an SVG image.
    • Send Response: Sends the SVG content as the response.
    • Error Handling: If the file is not found or any other error occurs, it returns the fallback.svg file.

Step 2: Using the API Endpoint
Now, if you open /api/img/1/logo.svg you should get that file, logo.svg, but if you change the “/1/” in the path by any number or string, you should get the fallback.svg file

By following these steps, you can create a Next.js API endpoint that returns SVG files. This approach is useful for serving dynamic SVGs, centralizing asset management, and adding access control to your SVG files. With the flexibility of Next.js API routes, you can easily integrate this functionality into your applications.

Esta entrada fue publicada en Informatica, Javascript y etiquetada , , , . Guarda el enlace permanente.

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos necesarios están marcados *


Puedes usar las siguientes etiquetas y atributos HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>