Skip to content

Commit a8bfade

Browse files
authored
fix: set basePath from next config as env variable (#15154)
### What Fix image preview URLs not displaying when `basePath` is set in `next.config.mjs`. ### Why When `basePath` is set in `next.config.mjs`, the `withPayload` function assigns it as an env variable. However, currently the file sets `basePath` as `baseConfig.env.NEXT_BASE_PATH`, which is only accessible in Next.js runtime contexts (API routes, server components). Upload URLs are generated from `formatAdminURL` in the Node.js environment, where `baseConfig.env.NEXT_BASE_PATH` cannot be accessed. As a result, it thinks no `basePath` is set and uses the incorrect URL to render the upload preview. ### Where `withPayload` now sets both `baseConfig.env.NEXT_BASE_PATH` **and** `process.env.NEXT_BASE_PATH`, making `basePath` available everywhere. Previously, users had to manually set `NEXT_BASE_PATH` in `.env` to work around this. ##### Fixes #15111
1 parent 88a901c commit a8bfade

2 files changed

Lines changed: 49 additions & 0 deletions

File tree

packages/next/src/withPayload/withPayload.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,7 @@ export const withPayload = (nextConfig = {}, options = {}) => {
208208
}
209209

210210
if (nextConfig.basePath) {
211+
process.env.NEXT_BASE_PATH = nextConfig.basePath
211212
baseConfig.env.NEXT_BASE_PATH = nextConfig.basePath
212213
}
213214

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import { describe, expect, it } from 'vitest'
2+
3+
import { withPayload } from './withPayload.js'
4+
5+
describe('withPayload', () => {
6+
it('should set process.env.NEXT_BASE_PATH when nextConfig.basePath is provided', () => {
7+
const originalBasePath = process.env.NEXT_BASE_PATH
8+
delete process.env.NEXT_BASE_PATH
9+
10+
try {
11+
const mockNextConfig = {
12+
basePath: '/test/basepath',
13+
}
14+
15+
withPayload(mockNextConfig)
16+
17+
// Verify it set the env var so formatAdminURL can read it
18+
expect(process.env.NEXT_BASE_PATH).toBe('/test/basepath')
19+
} finally {
20+
// Restore original value
21+
if (originalBasePath === undefined) {
22+
delete process.env.NEXT_BASE_PATH
23+
} else {
24+
process.env.NEXT_BASE_PATH = originalBasePath
25+
}
26+
}
27+
})
28+
29+
it('should not modify process.env.NEXT_BASE_PATH when basePath is not provided', () => {
30+
const originalBasePath = process.env.NEXT_BASE_PATH
31+
32+
try {
33+
const mockNextConfig = {}
34+
35+
withPayload(mockNextConfig)
36+
37+
// Verify it didn't set the env var
38+
expect(process.env.NEXT_BASE_PATH).toBe(originalBasePath)
39+
} finally {
40+
// Restore original value
41+
if (originalBasePath === undefined) {
42+
delete process.env.NEXT_BASE_PATH
43+
} else {
44+
process.env.NEXT_BASE_PATH = originalBasePath
45+
}
46+
}
47+
})
48+
})

0 commit comments

Comments
 (0)