Make sure Next has basePath before remounting baseUrl

This commit is contained in:
mikiher
2026-08-27 12:17:10 +03:00
parent 13432209ee
commit c0b9110e4e
+20 -1
View File
@@ -46,6 +46,18 @@ const passport = require('passport')
const expressSession = require('express-session') const expressSession = require('express-session')
const MemoryStore = require('./libs/memorystore') const MemoryStore = require('./libs/memorystore')
/**
* `next()` for a custom server is a NextCustomServer wrapper. After prepare(),
* `.server` is another NextServer wrapper; the Node server with `nextConfig` is
* one more `.server` down. Older react clients have no basePath and must keep
* Express-stripped URLs.
*/
function getPreparedNextBasePath(nextApp) {
const nodeServer = nextApp.server?.server
const basePath = nodeServer?.nextConfig?.basePath
return typeof basePath === 'string' ? basePath : ''
}
class Server { class Server {
constructor(SOURCE, PORT, HOST, CONFIG_PATH, METADATA_PATH, ROUTER_BASE_PATH) { constructor(SOURCE, PORT, HOST, CONFIG_PATH, METADATA_PATH, ROUTER_BASE_PATH) {
this.Port = PORT this.Port = PORT
@@ -415,11 +427,18 @@ class Server {
const nextApp = next({ dev: Logger.isDev, dir: ReactClientPath }) const nextApp = next({ dev: Logger.isDev, dir: ReactClientPath })
const handle = nextApp.getRequestHandler() const handle = nextApp.getRequestHandler()
await nextApp.prepare() await nextApp.prepare()
const nextBasePath = getPreparedNextBasePath(nextApp)
if (nextBasePath) {
Logger.info(`[Server] Next client basePath is "${nextBasePath}"`)
} else {
Logger.info(`[Server] Next client has no basePath; leaving Express-stripped URLs as-is`)
}
router.all('*', (req, res) => { router.all('*', (req, res) => {
// Next is configured with the same base path as this router, but Express strips the mount // Next is configured with the same base path as this router, but Express strips the mount
// prefix from req.url, so put it back. The bare mount path is passed through without a // prefix from req.url, so put it back. The bare mount path is passed through without a
// trailing slash, which Next would otherwise redirect away from on every request. // trailing slash, which Next would otherwise redirect away from on every request.
if (req.baseUrl) { // Skip when Next has no basePath (older client on master).
if (nextBasePath && req.baseUrl) {
const queryIndex = req.url.indexOf('?') const queryIndex = req.url.indexOf('?')
const pathname = queryIndex === -1 ? req.url : req.url.slice(0, queryIndex) const pathname = queryIndex === -1 ? req.url : req.url.slice(0, queryIndex)
const search = queryIndex === -1 ? '' : req.url.slice(queryIndex) const search = queryIndex === -1 ? '' : req.url.slice(queryIndex)