Next.js Discord

Discord Forum

images localPatterns + nextConfig basePath is not working

Answered
Yves posted this in #help-forum
Open in Discord
Answered by Yves
I resolved with a custom loaderFile:

https://nextjs.org/docs/app/api-reference/components/image#loaderfile

code:


// app/utils/image-loader.ts "use client"; export default function imageLoader({ src, width, quality, }: { src: string; width: number; quality?: number; }): string { let origin: string; if (typeof window !== "undefined") { origin = window.location.origin; } else { const protocol = process.env.NODE_ENV === "production" ? "https" : "http"; const host = process.env.NEXT_PUBLIC_SITE_URL || "localhost:3000"; origin = `${protocol}://${host}`; } const basePath = process.env.NEXT_PUBLIC_CUSTOMER || ""; const normalizedSrc = src.startsWith("/") ? src.slice(1) : src; return `${origin}/${basePath}/${normalizedSrc}?w=${width}&q=${quality ?? 75}`; }

next.config.ts

import type { NextConfig } from "next";
import CONSTANTS from "./constants";

const { NEXT_PUBLIC_CUSTOMER } = CONSTANTS.APP_ENV;

const nextConfig: NextConfig = {
assetPrefix: "/volta-redonda",
basePath: /${NEXT_PUBLIC_CUSTOMER},
images: {
loader: "custom",
loaderFile: "/utils/image-loader.ts",
localPatterns: [
{
pathname: /${NEXT_PUBLIC_CUSTOMER}/**,
search: "",
},
],
},
async redirects() {
return [
{
source: "/",
basePath: false,
destination: /${NEXT_PUBLIC_CUSTOMER},
permanent: true,
},
];
},
};

export default nextConfig;
View full answer

1 Reply

I resolved with a custom loaderFile:

https://nextjs.org/docs/app/api-reference/components/image#loaderfile

code:


// app/utils/image-loader.ts "use client"; export default function imageLoader({ src, width, quality, }: { src: string; width: number; quality?: number; }): string { let origin: string; if (typeof window !== "undefined") { origin = window.location.origin; } else { const protocol = process.env.NODE_ENV === "production" ? "https" : "http"; const host = process.env.NEXT_PUBLIC_SITE_URL || "localhost:3000"; origin = `${protocol}://${host}`; } const basePath = process.env.NEXT_PUBLIC_CUSTOMER || ""; const normalizedSrc = src.startsWith("/") ? src.slice(1) : src; return `${origin}/${basePath}/${normalizedSrc}?w=${width}&q=${quality ?? 75}`; }

next.config.ts

import type { NextConfig } from "next";
import CONSTANTS from "./constants";

const { NEXT_PUBLIC_CUSTOMER } = CONSTANTS.APP_ENV;

const nextConfig: NextConfig = {
assetPrefix: "/volta-redonda",
basePath: /${NEXT_PUBLIC_CUSTOMER},
images: {
loader: "custom",
loaderFile: "/utils/image-loader.ts",
localPatterns: [
{
pathname: /${NEXT_PUBLIC_CUSTOMER}/**,
search: "",
},
],
},
async redirects() {
return [
{
source: "/",
basePath: false,
destination: /${NEXT_PUBLIC_CUSTOMER},
permanent: true,
},
];
},
};

export default nextConfig;
Answer