I have the following in my next.config.js:
/** @type {import('next').NextConfig} */
const nextConfig = {
output: "standalone",
// If set, use the given URL prefix for fetching static content instead of serving
// it directly from the next app.
assetPrefix: process.env.NEXT_PUBLIC_CDN_PREFIX,
};
The focus here is assetPrefix
. I want this value to be read at runtime to inform the client where to fetch static assets. The issue is, even though I have this env var set, it doesn't work because I believe the final value for assetPrefix
is determined at build time, but the env var is only set during run time.
For the rest of my app I'm solving this by using next-runtime-env but I can't seem to get that to work in next.config.js
.
Is there a way to set assetPrefix
based on an env var at runtime?
I'm running NextJS from a Docker image. I build the app as part of building the image, which I'd prefer to keep doing rather than building as part of the command when I run a container from that image. I suspect you could solve this with middleware instead of assetPrefix
but I'd rather use what NextJS provides out of the box.
I'm using NextJS version 14.0.2 and next-runtime-env 3.0.1.
While accessing runtime env vars is not possible for assetPrefix
in next.config.js
, you can achieve the same goal by instead using middleware. To do this, create a file called middleware.ts
in the root of your app (e.g. src/
), with content like this:
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
// If NEXT_PUBLIC_CDN_PREFIX is set, redirect requests for static content to the CDN.
export function middleware(request: NextRequest) {
// If the env var is not set, just forward the request to the next middleware.
if (process.env.NEXT_PUBLIC_CDN_PREFIX === undefined) {
return NextResponse.next();
}
// Build a new URL with the CDN prefix as the hostname.
const { nextUrl } = request;
const { pathname } = nextUrl;
const destinationURL = `${process.env.NEXT_PUBLIC_CDN_PREFIX}${pathname}`;
return NextResponse.redirect(destinationURL);
}
// Run the middleware for all requests to the static content path.
export const config = {
matcher: "/_next/static/(.*)",
};
See more about this topic here:
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments