Skip to content

How to Fix Can't Load Image in Vercel Production

Published: at 02:54 PM

This happened a few weeks ago, when I deployed to Vercel and everything seemed to be working until I visited the deployment URL and, guess what? the image didn’t load. When deploying Next.js projects on Vercel, you may encounter issues with images not loading properly. This can be frustrating, but it is a common issue that can be resolved by updating your middleware.ts file to handle matches correctly. Below is a comprehensive guide on how to resolve this problem in a few simple steps.

Understanding the Issue

The error occurs because of incorrect route handling in the middleware.ts file. Vercel requires specific rules to ensure that the images load properly in production. Without these configurations, your Next.js app may fail to display images.

Update the middleware.ts for Proper Routing

To fix the issue, you need to update the matching rules in your middleware.ts. By doing this, you ensure that the correct routes are used to load images.

Step 1: Open the middleware.ts File

Navigate to the root of your Next.js project and locate the middleware.ts file. This file is responsible for handling routing and middleware in your application.

Step 2: Modify the Matches in middleware.ts

Within the middleware.ts, locate the section that deals with route matching. Update the matching pattern to include image routes properly. Below is an example of how to adjust the code:

import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

import { auth0Config } from "@/lib/auth0/config";

const auth0Edge = initAuth0Edge(auth0Config);

export default async function middleware(request: NextRequest) {
  const response = NextResponse.next();
  const session = await auth0Edge.getSession(request, response);

  if (!session) {
    // Redirect to login page if not logged in
    const url = new URL("/api/auth/login", request.url);
    return NextResponse.redirect(url);
  }

  return response;
}

export const config = {
  matcher:
    "/((?!api/auth|_next/static|_next/image|favicon.png|public|svg|images).*)",
};

Remember is to include public in your matcher to load the images from public folder properly!

Final Thoughts

Fixing the “Can’t Load Image” issue in Vercel production for Next.js projects can be easily resolved by updating your middleware.ts file. By ensuring that image routes are handled correctly, you can avoid this common issue and provide a seamless experience for users.

Now that your images are loading correctly, you can focus on enhancing other aspects of your Next.js project without worrying about missing visuals! Happy coding!