Next JS Images after next build gives 404 images

Viewed 1382

Default URL structure is http://localhost:5000/_next/image?url="someURL".

I want the URL to be like http://localhost:5000/demo/_next/image?url="someURL".

which can be achieved by

// next.config.js
     images: {
            domains: ['example.domain.com'],
            path: `/demo/_next/image`
        },

In this, the _next/image where the directory is pointing cannot be found.

After this, all the images are giving 404. I need a solution to this problem in the next js.

1 Answers

Have you tried to create a middleware to rewrite those routes to the correct location?

Something like: pages/_middleware.ts with content:

import { NextRequest, NextResponse } from 'next/server';

export function middleware(req: NextRequest): NextResponse {
  if (req.nextUrl.href.includes('/demo/_next/image'))
    return NextResponse.rewrite(
      req.nextUrl.href.replace('/demo/_next/image', '/_next/image'),
    );

  return null;
}
Related