Skip to content

Use middleware to handle routing image requests to Drupal #871

@longwave

Description

@longwave

Package

next-drupal (NPM package)

Describe the feature request

At the moment to use the Image component in Next.js you are expected to prepend image URLs from Drupal with the public base URL. This either means adding a wrapper component or remembering to do it everywhere you use images.

Describe the solution you'd like

Use middleware instead to automatically route /sites/default/files/ to the Drupal backend. This also means you don't have to add to remotePatterns in Next.js config, because the images are considered to be local.

This works for me in a middleware.ts:

export function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl

  // Rewrite local image requests to the Drupal site.
  if (
    pathname.startsWith('/sites/default/files/') &&
    process.env.NEXT_PUBLIC_DRUPAL_BASE_URL
  ) {
    const remoteUrl = process.env.NEXT_PUBLIC_DRUPAL_BASE_URL.concat(pathname)
    return NextResponse.rewrite(remoteUrl)
  }

  return NextResponse.next()
  )
}

It would be great if this was considered as an out-of-the-box solution for image handling.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requesttriageA new issue that needs triage

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions