Dynamic Image Resizing with Next.js API Routes

Create an API route in Next.js that uses sharp to dynamically resize images based on query parameters, reducing image size before sending it to the client.
import { NextApiRequest, NextApiResponse } from 'next';
import sharp from 'sharp';
import { promises as fsPromises } from 'fs';
import path from 'path';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const { width, height, src } = req.query;

  const widthInt = parseInt(width, 10) || null;
  const heightInt = parseInt(height, 10) || null;

  if (!src || Array.isArray(src)) {
    res.status(400).send('Invalid image source');

  const filePath = path.resolve('.', `public/${src}`);
  let resizedImageBuffer;

  try {
    resizedImageBuffer = await sharp(filePath)
      .resize(widthInt, heightInt)
  } catch (error) {
    res.status(500).send('Error resizing image');

  res.setHeader('Content-Type', 'image/jpeg');
This code sets up an API route in Next.js that takes query parameters for width, height, and image source (src). It uses the sharp library to read the specified image from the 'public' directory, resize it according to the provided dimensions, and then return the resized image as a JPEG buffer. The code includes error handling for invalid source and resizing errors.
import { existsSync } from 'fs';

if (!existsSync(filePath)) {
  res.status(404).send('Image not found');
This snippet checks if the image file exists at the specified file path. It sends a 404 status code if the image is not found to prevent sharp from trying to resize a non-existent file.