How to Set the Base Path for Optimized Images in Next.js

To set the basePath for optimized images in Next.js, define the same basePath value in both your next.config.js and your next-export-optimize-images configuration file so the library can correctly resolve URLs at build time and runtime.

When deploying a Next.js application to a subdirectory (like /blog or /docs), you must configure the basePath in two places: the standard Next.js configuration and the next-export-optimize-images library configuration. This ensures that the next-export-optimize-images library (maintained by dc7290/next-export-optimize-images) generates correct image URLs that respect your site's sub-path routing.

Why Base Path Configuration Matters

If your Next.js site lives under a sub-path such as https://example.com/docs/, the basePath setting tells Next.js to prefix all routes with /docs. However, the image optimizer also needs this information to strip the base path from source file locations during optimization and prepend it to final image URLs when rendering. Without mirroring this setting in the optimizer config, your images will either fail to load or resolve to incorrect paths.

Configuring basePath in next-export-optimize-images

Step 1: Define basePath in next.config.js

First, set the base path in your standard Next.js configuration file. This affects routing for your entire application.

// next.config.js
module.exports = {
  basePath: '/docs',
  // Other Next.js options...
}

Step 2: Mirror the Setting in the Optimizer Config

Create or update your optimizer configuration file (commonly next-export-optimize-images.config.mjs or next-export-optimize-images.config.js). According to the source code in src/utils/getConfig.ts (lines 39-44), you must provide an identical basePath value here:

// src/utils/getConfig.ts (excerpt)
/**
 * Required if you have set basePath in next.config.js.
 * Please set the same value.
 *
 * @type {string}
 */
basePath?: string

Add the matching configuration to your optimizer config file:

// next-export-optimize-images.config.mjs
export default {
  basePath: '/docs',  // Must exactly match next.config.js
  outDir: 'out',
  imageDir: '_next/static/chunks/images',
  // Additional optimizer options...
}

Step 3: Verify the Generated Output

After running the export command, inspect the generated HTML. The image src attributes should include the base path prefix:

<img
  src="/docs/_next/static/chunks/images/hero-800w.webp"
  width="800"
  height="400"
  alt="Hero image"
/>

How the Library Processes basePath Internally

The next-export-optimize-images library handles basePath in two distinct phases to ensure correct path resolution.

Build-Time Path Stripping

During the build process, the optimizer must remove the basePath from the original image source path to generate clean output filenames. This logic is implemented in src/utils/buildOutputInfo.ts (lines 39-45):

// src/utils/buildOutputInfo.ts (excerpt)
if (config.basePath !== undefined) {
  src = _src.replace(config.basePath, '')
}

This ensures that an image referenced as /docs/images/photo.jpg is processed as if it were located at /images/photo.jpg, preventing duplicate folder structures in the output directory.

Runtime URL Construction

When the image loader renders the final <img> tag in the browser, it prepends the basePath to the optimized file path. This happens in src/components/utils/imageLoader.ts (line 22):

// src/components/utils/imageLoader.ts (excerpt)
return `${config.basePath ?? ''}${outputInfo.output}`

If basePath is undefined, it defaults to an empty string, maintaining compatibility with sites deployed at the root domain.

Summary

  • Mirroring is mandatory: The basePath in next-export-optimize-images.config.mjs must exactly match the value in next.config.js.
  • Build-time processing: The optimizer strips basePath from source paths in src/utils/buildOutputInfo.ts to generate correct output filenames.
  • Runtime assembly: The image loader prepends basePath to optimized image URLs in src/components/utils/imageLoader.ts.
  • File location: Store your optimizer configuration in the project root as next-export-optimize-images.config.mjs (or .js, .ts variants supported by the library).

Frequently Asked Questions

What happens if I don't set basePath in the optimizer config?

If you omit the basePath setting in the optimizer configuration while using one in next.config.js, the library will generate image URLs without the subdirectory prefix, causing 404 errors when the site is deployed. Additionally, the build process may create incorrect folder structures because it won't strip the basePath from source file locations.

Can I use environment variables to set the basePath?

Yes, the library supports dynamic configuration. You can load the basePath from environment variables in your next-export-optimize-images.config.mjs file using process.env.NEXT_PUBLIC_BASE_PATH or similar, as long as the final exported configuration object contains the correct string value that matches your Next.js config.

Does basePath affect the image optimization quality or format?

No, the basePath setting is purely for URL path resolution and routing. It does not influence image compression settings, output formats (WebP, AVIF), or quality parameters. Those are controlled by separate configuration options like quality or convertFormat in the optimizer config.

Where should I place the next-export-optimize-images config file?

Place the configuration file in your project root directory. The library searches for next-export-optimize-images.config.mjs, .js, .ts, or .mts files by default. Alternatively, you can specify a custom path using the --config CLI flag when running the export command.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →