UNPKG

next

Version:

The React Framework

988 lines (987 loc) • 67.1 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.prepareServerlessUrl = prepareServerlessUrl; Object.defineProperty(exports, "stringifyQuery", { enumerable: true, get: function() { return _serverRouteUtils.stringifyQuery; } }); exports.default = void 0; var _utils = require("../shared/lib/utils"); var _path = require("../shared/lib/isomorphic/path"); var _querystring = require("querystring"); var _url = require("url"); var _redirectStatus = require("../lib/redirect-status"); var _constants = require("../shared/lib/constants"); var _utils1 = require("../shared/lib/router/utils"); var _apiUtils = require("./api-utils"); var envConfig = _interopRequireWildcard(require("../shared/lib/runtime-config")); var _utils2 = require("./utils"); var _router = _interopRequireDefault(require("./router")); var _pathMatch = require("../shared/lib/router/utils/path-match"); var _revalidateHeaders = require("./send-payload/revalidate-headers"); var _incrementalCache = require("./lib/incremental-cache"); var _renderResult = _interopRequireDefault(require("./render-result")); var _removeTrailingSlash = require("../shared/lib/router/utils/remove-trailing-slash"); var _getRouteFromAssetPath = _interopRequireDefault(require("../shared/lib/router/utils/get-route-from-asset-path")); var _denormalizePagePath = require("../shared/lib/page-path/denormalize-page-path"); var _normalizeLocalePath = require("../shared/lib/i18n/normalize-locale-path"); var Log = _interopRequireWildcard(require("../build/output/log")); var _detectDomainLocale = require("../shared/lib/i18n/detect-domain-locale"); var _escapePathDelimiters = _interopRequireDefault(require("../shared/lib/router/utils/escape-path-delimiters")); var _utils3 = require("../build/webpack/loaders/next-serverless-loader/utils"); var _responseCache = _interopRequireDefault(require("./response-cache")); var _isError = _interopRequireWildcard(require("../lib/is-error")); var _requestMeta = require("./request-meta"); var _serverRouteUtils = require("./server-route-utils"); var _removePathPrefix = require("../shared/lib/router/utils/remove-path-prefix"); var _appPaths = require("../shared/lib/router/utils/app-paths"); var _routeMatcher = require("../shared/lib/router/utils/route-matcher"); var _routeRegex = require("../shared/lib/router/utils/route-regex"); var _getLocaleRedirect = require("../shared/lib/i18n/get-locale-redirect"); var _getHostname = require("../shared/lib/get-hostname"); var _parseUrl = require("../shared/lib/router/utils/parse-url"); var _getNextPathnameInfo = require("../shared/lib/router/utils/get-next-pathname-info"); var _normalizePagePath = require("../shared/lib/page-path/normalize-page-path"); class Server { constructor(options){ var ref, ref1, ref2; const { dir ="." , quiet =false , conf , dev =false , minimalMode =false , customServer =true , hostname , port , } = options; this.serverOptions = options; this.dir = (0, _path).resolve(dir); this.quiet = quiet; this.loadEnvConfig({ dev }); // TODO: should conf be normalized to prevent missing // values from causing issues as this can be user provided this.nextConfig = conf; this.hostname = hostname; this.port = port; this.distDir = (0, _path).join(this.dir, this.nextConfig.distDir); this.publicDir = this.getPublicDir(); this.hasStaticDir = !minimalMode && this.getHasStaticDir(); // Only serverRuntimeConfig needs the default // publicRuntimeConfig gets it's default in client/index.js const { serverRuntimeConfig ={} , publicRuntimeConfig , assetPrefix , generateEtags , } = this.nextConfig; this.buildId = this.getBuildId(); this.minimalMode = minimalMode || !!process.env.NEXT_PRIVATE_MINIMAL_MODE; const serverComponents = this.nextConfig.experimental.serverComponents; this.serverComponentManifest = serverComponents ? this.getServerComponentManifest() : undefined; this.renderOpts = { poweredByHeader: this.nextConfig.poweredByHeader, canonicalBase: this.nextConfig.amp.canonicalBase || "", buildId: this.buildId, generateEtags, previewProps: this.getPreviewProps(), customServer: customServer === true ? true : undefined, ampOptimizerConfig: (ref = this.nextConfig.experimental.amp) == null ? void 0 : ref.optimizer, basePath: this.nextConfig.basePath, images: this.nextConfig.images, optimizeFonts: !!this.nextConfig.optimizeFonts && !dev, fontManifest: this.nextConfig.optimizeFonts && !dev ? this.getFontManifest() : undefined, optimizeCss: this.nextConfig.experimental.optimizeCss, nextScriptWorkers: this.nextConfig.experimental.nextScriptWorkers, disableOptimizedLoading: this.nextConfig.experimental.runtime ? true : this.nextConfig.experimental.disableOptimizedLoading, domainLocales: (ref1 = this.nextConfig.i18n) == null ? void 0 : ref1.domains, distDir: this.distDir, runtime: this.nextConfig.experimental.runtime, serverComponents, crossOrigin: this.nextConfig.crossOrigin ? this.nextConfig.crossOrigin : undefined, largePageDataBytes: this.nextConfig.experimental.largePageDataBytes }; // Only the `publicRuntimeConfig` key is exposed to the client side // It'll be rendered as part of __NEXT_DATA__ on the client side if (Object.keys(publicRuntimeConfig).length > 0) { this.renderOpts.runtimeConfig = publicRuntimeConfig; } // Initialize next/config with the environment configuration envConfig.setConfig({ serverRuntimeConfig, publicRuntimeConfig }); this.pagesManifest = this.getPagesManifest(); this.appPathsManifest = this.getAppPathsManifest(); this.customRoutes = this.getCustomRoutes(); this.router = new _router.default(this.generateRoutes()); this.setAssetPrefix(assetPrefix); this.incrementalCache = new _incrementalCache.IncrementalCache({ fs: this.getCacheFilesystem(), dev, serverDistDir: this.serverDistDir, maxMemoryCacheSize: this.nextConfig.experimental.isrMemoryCacheSize, flushToDisk: !minimalMode && this.nextConfig.experimental.isrFlushToDisk, incrementalCacheHandlerPath: (ref2 = this.nextConfig.experimental) == null ? void 0 : ref2.incrementalCacheHandlerPath, getPrerenderManifest: ()=>{ if (dev) { return { version: -1, routes: {}, dynamicRoutes: {}, notFoundRoutes: [], preview: null }; } else { return this.getPrerenderManifest(); } } }); this.responseCache = new _responseCache.default(this.incrementalCache, this.minimalMode); } logError(err) { if (this.quiet) return; console.error(err); } async handleRequest(req, res, parsedUrl) { try { var ref, ref3; const urlParts = (req.url || "").split("?"); const urlNoQuery = urlParts[0]; if (urlNoQuery == null ? void 0 : urlNoQuery.match(/(\\|\/\/)/)) { const cleanUrl = (0, _utils).normalizeRepeatedSlashes(req.url); res.redirect(cleanUrl, 308).body(cleanUrl).send(); return; } (0, _apiUtils).setLazyProp({ req: req }, "cookies", (0, _apiUtils).getCookieParser(req.headers)); // Parse url if parsedUrl not provided if (!parsedUrl || typeof parsedUrl !== "object") { parsedUrl = (0, _url).parse(req.url, true); } // Parse the querystring ourselves if the user doesn't handle querystring parsing if (typeof parsedUrl.query === "string") { parsedUrl.query = (0, _querystring).parse(parsedUrl.query); } this.attachRequestMeta(req, parsedUrl); const domainLocale = (0, _detectDomainLocale).detectDomainLocale((ref = this.nextConfig.i18n) == null ? void 0 : ref.domains, (0, _getHostname).getHostname(parsedUrl, req.headers)); const defaultLocale = (domainLocale == null ? void 0 : domainLocale.defaultLocale) || ((ref3 = this.nextConfig.i18n) == null ? void 0 : ref3.defaultLocale); const url = (0, _parseUrl).parseUrl(req.url.replace(/^\/+/, "/")); const pathnameInfo = (0, _getNextPathnameInfo).getNextPathnameInfo(url.pathname, { nextConfig: this.nextConfig }); url.pathname = pathnameInfo.pathname; if (pathnameInfo.basePath) { req.url = (0, _removePathPrefix).removePathPrefix(req.url, this.nextConfig.basePath); (0, _requestMeta).addRequestMeta(req, "_nextHadBasePath", true); } if (this.minimalMode && typeof req.headers["x-matched-path"] === "string") { try { // x-matched-path is the source of truth, it tells what page // should be rendered because we don't process rewrites in minimalMode let matchedPath = new URL(req.headers["x-matched-path"], "http://localhost").pathname; let urlPathname = new URL(req.url, "http://localhost").pathname; // For ISR the URL is normalized to the prerenderPath so if // it's a data request the URL path will be the data URL, // basePath is already stripped by this point if (urlPathname.startsWith(`/_next/data/`)) { parsedUrl.query.__nextDataReq = "1"; } const normalizedUrlPath = this.stripNextDataPath(urlPathname); matchedPath = this.stripNextDataPath(matchedPath, false); if (this.nextConfig.i18n) { const localeResult = (0, _normalizeLocalePath).normalizeLocalePath(matchedPath, this.nextConfig.i18n.locales); matchedPath = localeResult.pathname; if (localeResult.detectedLocale) { parsedUrl.query.__nextLocale = localeResult.detectedLocale; } } matchedPath = (0, _denormalizePagePath).denormalizePagePath(matchedPath); let srcPathname = matchedPath; if (!(0, _utils1).isDynamicRoute(srcPathname) && !await this.hasPage((0, _removeTrailingSlash).removeTrailingSlash(srcPathname))) { for (const dynamicRoute of this.dynamicRoutes || []){ if (dynamicRoute.match(srcPathname)) { srcPathname = dynamicRoute.page; break; } } } const pageIsDynamic = (0, _utils1).isDynamicRoute(srcPathname); const utils = (0, _utils3).getUtils({ pageIsDynamic, page: srcPathname, i18n: this.nextConfig.i18n, basePath: this.nextConfig.basePath, rewrites: this.customRoutes.rewrites }); // ensure parsedUrl.pathname includes URL before processing // rewrites or they won't match correctly if (defaultLocale && !pathnameInfo.locale) { parsedUrl.pathname = `/${defaultLocale}${parsedUrl.pathname}`; } const pathnameBeforeRewrite = parsedUrl.pathname; const rewriteParams = utils.handleRewrites(req, parsedUrl); const rewriteParamKeys = Object.keys(rewriteParams); const didRewrite = pathnameBeforeRewrite !== parsedUrl.pathname; if (didRewrite) { (0, _requestMeta).addRequestMeta(req, "_nextRewroteUrl", parsedUrl.pathname); (0, _requestMeta).addRequestMeta(req, "_nextDidRewrite", true); } // interpolate dynamic params and normalize URL if needed if (pageIsDynamic) { let params = {}; let paramsResult = utils.normalizeDynamicRouteParams(parsedUrl.query); // for prerendered ISR paths we attempt parsing the route // params from the URL directly as route-matches may not // contain the correct values due to the filesystem path // matching before the dynamic route has been matched if (!paramsResult.hasValidParams && pageIsDynamic && !(0, _utils1).isDynamicRoute(normalizedUrlPath)) { let matcherParams = utils.dynamicRouteMatcher == null ? void 0 : utils.dynamicRouteMatcher(normalizedUrlPath); if (matcherParams) { utils.normalizeDynamicRouteParams(matcherParams); Object.assign(paramsResult.params, matcherParams); paramsResult.hasValidParams = true; } } if (paramsResult.hasValidParams) { params = paramsResult.params; } if (req.headers["x-now-route-matches"] && (0, _utils1).isDynamicRoute(matchedPath) && !paramsResult.hasValidParams) { const opts = {}; const routeParams = utils.getParamsFromRouteMatches(req, opts, parsedUrl.query.__nextLocale || ""); if (opts.locale) { parsedUrl.query.__nextLocale = opts.locale; } paramsResult = utils.normalizeDynamicRouteParams(routeParams, true); if (paramsResult.hasValidParams) { params = paramsResult.params; } } // handle the actual dynamic route name being requested if (pageIsDynamic && utils.defaultRouteMatches && normalizedUrlPath === srcPathname && !paramsResult.hasValidParams && !utils.normalizeDynamicRouteParams({ ...params }, true).hasValidParams) { params = utils.defaultRouteMatches; } if (params) { matchedPath = utils.interpolateDynamicPath(srcPathname, params); req.url = utils.interpolateDynamicPath(req.url, params); } Object.assign(parsedUrl.query, params); } if (pageIsDynamic || didRewrite) { var ref4; utils.normalizeVercelUrl(req, true, [ ...rewriteParamKeys, ...Object.keys(((ref4 = utils.defaultRouteRegex) == null ? void 0 : ref4.groups) || {}), ]); } parsedUrl.pathname = `${this.nextConfig.basePath || ""}${matchedPath === "/" && this.nextConfig.basePath ? "" : matchedPath}`; url.pathname = parsedUrl.pathname; } catch (err) { if (err instanceof _utils.DecodeError || err instanceof _utils.NormalizeError) { res.statusCode = 400; return this.renderError(null, req, res, "/_error", {}); } throw err; } } (0, _requestMeta).addRequestMeta(req, "__nextHadTrailingSlash", pathnameInfo.trailingSlash); (0, _requestMeta).addRequestMeta(req, "__nextIsLocaleDomain", Boolean(domainLocale)); parsedUrl.query.__nextDefaultLocale = defaultLocale; if (pathnameInfo.locale) { req.url = (0, _url).format(url); (0, _requestMeta).addRequestMeta(req, "__nextStrippedLocale", true); } if (!this.minimalMode || !parsedUrl.query.__nextLocale) { if (pathnameInfo.locale || defaultLocale) { parsedUrl.query.__nextLocale = pathnameInfo.locale || defaultLocale; } } if (!this.minimalMode && defaultLocale) { const redirect = (0, _getLocaleRedirect).getLocaleRedirect({ defaultLocale, domainLocale, headers: req.headers, nextConfig: this.nextConfig, pathLocale: pathnameInfo.locale, urlParsed: { ...url, pathname: pathnameInfo.locale ? `/${pathnameInfo.locale}${url.pathname}` : url.pathname } }); if (redirect) { return res.redirect(redirect, _constants.TEMPORARY_REDIRECT_STATUS).body(redirect).send(); } } res.statusCode = 200; return await this.run(req, res, parsedUrl); } catch (err) { if (err && typeof err === "object" && err.code === "ERR_INVALID_URL" || err instanceof _utils.DecodeError || err instanceof _utils.NormalizeError) { res.statusCode = 400; return this.renderError(null, req, res, "/_error", {}); } if (this.minimalMode || this.renderOpts.dev) { throw err; } this.logError((0, _isError).getProperError(err)); res.statusCode = 500; res.body("Internal Server Error").send(); } } getRequestHandler() { return this.handleRequest.bind(this); } async handleUpgrade(_req, _socket, _head) {} setAssetPrefix(prefix) { this.renderOpts.assetPrefix = prefix ? prefix.replace(/\/$/, "") : ""; } // Backwards compatibility async prepare() {} // Backwards compatibility async close() {} getCustomRoutes() { const customRoutes = this.getRoutesManifest(); let rewrites; // rewrites can be stored as an array when an array is // returned in next.config.js so massage them into // the expected object format if (Array.isArray(customRoutes.rewrites)) { rewrites = { beforeFiles: [], afterFiles: customRoutes.rewrites, fallback: [] }; } else { rewrites = customRoutes.rewrites; } return Object.assign(customRoutes, { rewrites }); } getFallback(page) { page = (0, _normalizePagePath).normalizePagePath(page); const cacheFs = this.getCacheFilesystem(); return cacheFs.readFile((0, _path).join(this.serverDistDir, "pages", `${page}.html`)); } getPreviewProps() { return this.getPrerenderManifest().preview; } generateRoutes() { const publicRoutes = this.generatePublicRoutes(); const imageRoutes = this.generateImageRoutes(); const staticFilesRoutes = this.generateStaticRoutes(); const fsRoutes = [ ...this.generateFsStaticRoutes(), { match: (0, _pathMatch).getPathMatch("/_next/data/:path*"), type: "route", name: "_next/data catchall", check: true, fn: async (req, res, params, _parsedUrl)=>{ // Make sure to 404 for /_next/data/ itself and // we also want to 404 if the buildId isn't correct if (!params.path || params.path[0] !== this.buildId) { await this.render404(req, res, _parsedUrl); return { finished: true }; } // remove buildId from URL params.path.shift(); const lastParam = params.path[params.path.length - 1]; // show 404 if it doesn't end with .json if (typeof lastParam !== "string" || !lastParam.endsWith(".json")) { await this.render404(req, res, _parsedUrl); return { finished: true }; } // re-create page's pathname let pathname = `/${params.path.join("/")}`; pathname = (0, _getRouteFromAssetPath).default(pathname, ".json"); // ensure trailing slash is normalized per config if (this.router.catchAllMiddleware[0]) { if (this.nextConfig.trailingSlash && !pathname.endsWith("/")) { pathname += "/"; } if (!this.nextConfig.trailingSlash && pathname.length > 1 && pathname.endsWith("/")) { pathname = pathname.substring(0, pathname.length - 1); } } if (this.nextConfig.i18n) { const { host } = (req == null ? void 0 : req.headers) || {}; // remove port from host and remove port if present const hostname = host == null ? void 0 : host.split(":")[0].toLowerCase(); const localePathResult = (0, _normalizeLocalePath).normalizeLocalePath(pathname, this.nextConfig.i18n.locales); const { defaultLocale } = (0, _detectDomainLocale).detectDomainLocale(this.nextConfig.i18n.domains, hostname) || {}; let detectedLocale = ""; if (localePathResult.detectedLocale) { pathname = localePathResult.pathname; detectedLocale = localePathResult.detectedLocale; } _parsedUrl.query.__nextLocale = detectedLocale; _parsedUrl.query.__nextDefaultLocale = defaultLocale || this.nextConfig.i18n.defaultLocale; if (!detectedLocale && !this.router.catchAllMiddleware[0]) { _parsedUrl.query.__nextLocale = _parsedUrl.query.__nextDefaultLocale; await this.render404(req, res, _parsedUrl); return { finished: true }; } } return { pathname, query: { ..._parsedUrl.query, __nextDataReq: "1" }, finished: false }; } }, ...imageRoutes, { match: (0, _pathMatch).getPathMatch("/_next/:path*"), type: "route", name: "_next catchall", // This path is needed because `render()` does a check for `/_next` and the calls the routing again fn: async (req, res, _params, parsedUrl)=>{ await this.render404(req, res, parsedUrl); return { finished: true }; } }, ...publicRoutes, ...staticFilesRoutes, ]; const restrictedRedirectPaths = this.nextConfig.basePath ? [ `${this.nextConfig.basePath}/_next` ] : [ "/_next" ]; // Headers come very first const headers = this.minimalMode ? [] : this.customRoutes.headers.map((rule)=>(0, _serverRouteUtils).createHeaderRoute({ rule, restrictedRedirectPaths })); const redirects = this.minimalMode ? [] : this.customRoutes.redirects.map((rule)=>(0, _serverRouteUtils).createRedirectRoute({ rule, restrictedRedirectPaths })); const rewrites = this.generateRewrites({ restrictedRedirectPaths }); const catchAllMiddleware = this.generateCatchAllMiddlewareRoute(); const catchAllRoute = { match: (0, _pathMatch).getPathMatch("/:path*"), type: "route", matchesLocale: true, name: "Catchall render", fn: async (req, res, _params, parsedUrl)=>{ let { pathname , query } = parsedUrl; if (!pathname) { throw new Error("pathname is undefined"); } // next.js core assumes page path without trailing slash pathname = (0, _removeTrailingSlash).removeTrailingSlash(pathname); if (this.nextConfig.i18n) { var ref; const localePathResult = (0, _normalizeLocalePath).normalizeLocalePath(pathname, (ref = this.nextConfig.i18n) == null ? void 0 : ref.locales); if (localePathResult.detectedLocale) { pathname = localePathResult.pathname; parsedUrl.query.__nextLocale = localePathResult.detectedLocale; } } const bubbleNoFallback = !!query._nextBubbleNoFallback; if (pathname === "/api" || pathname.startsWith("/api/")) { delete query._nextBubbleNoFallback; const handled = await this.handleApiRequest(req, res, pathname, query); if (handled) { return { finished: true }; } } try { await this.render(req, res, pathname, query, parsedUrl, true); return { finished: true }; } catch (err) { if (err instanceof NoFallbackError && bubbleNoFallback) { return { finished: false }; } throw err; } } }; const { useFileSystemPublicRoutes } = this.nextConfig; if (useFileSystemPublicRoutes) { this.appPathRoutes = this.getAppPathRoutes(); this.dynamicRoutes = this.getDynamicRoutes(); } return { headers, fsRoutes, rewrites, redirects, catchAllRoute, catchAllMiddleware, useFileSystemPublicRoutes, dynamicRoutes: this.dynamicRoutes, pageChecker: this.hasPage.bind(this), nextConfig: this.nextConfig }; } async hasPage(pathname) { let found = false; try { var ref; found = !!this.getPagePath(pathname, (ref = this.nextConfig.i18n) == null ? void 0 : ref.locales); } catch (_) {} return found; } async _beforeCatchAllRender(_req, _res, _params, _parsedUrl) { return false; } // Used to build API page in development async ensureApiPage(_pathname) {} /** * Resolves `API` request, in development builds on demand * @param req http request * @param res http response * @param pathname path of request */ async handleApiRequest(req, res, pathname, query) { let page = pathname; let params = undefined; let pageFound = !(0, _utils1).isDynamicRoute(page) && await this.hasPage(page); if (!pageFound && this.dynamicRoutes) { for (const dynamicRoute of this.dynamicRoutes){ params = dynamicRoute.match(pathname) || undefined; if (dynamicRoute.page.startsWith("/api") && params) { page = dynamicRoute.page; pageFound = true; break; } } } if (!pageFound) { return false; } // Make sure the page is built before getting the path // or else it won't be in the manifest yet await this.ensureApiPage(page); let builtPagePath; try { builtPagePath = this.getPagePath(page); } catch (err) { if ((0, _isError).default(err) && err.code === "ENOENT") { return false; } throw err; } return this.runApi(req, res, query, params, page, builtPagePath); } getDynamicRoutes() { const addedPages = new Set(); return (0, _utils1).getSortedRoutes([ ...Object.keys(this.appPathRoutes || {}), ...Object.keys(this.pagesManifest), ].map((page)=>{ var ref; return (0, _normalizeLocalePath).normalizeLocalePath(page, (ref = this.nextConfig.i18n) == null ? void 0 : ref.locales).pathname; })).map((page)=>{ if (addedPages.has(page) || !(0, _utils1).isDynamicRoute(page)) return null; addedPages.add(page); return { page, match: (0, _routeMatcher).getRouteMatcher((0, _routeRegex).getRouteRegex(page)) }; }).filter((item)=>Boolean(item)); } getAppPathRoutes() { const appPathRoutes = {}; Object.keys(this.appPathsManifest || {}).forEach((entry)=>{ if (entry.endsWith(_constants.NEXT_CLIENT_SSR_ENTRY_SUFFIX)) { return; } appPathRoutes[(0, _appPaths).normalizeAppPath(entry) || "/"] = entry; }); return appPathRoutes; } async run(req, res, parsedUrl) { this.handleCompression(req, res); try { const matched = await this.router.execute(req, res, parsedUrl); if (matched) { return; } } catch (err) { if (err instanceof _utils.DecodeError || err instanceof _utils.NormalizeError) { res.statusCode = 400; return this.renderError(null, req, res, "/_error", {}); } throw err; } await this.render404(req, res, parsedUrl); } async pipe(fn, partialContext) { const isBotRequest = (0, _utils2).isBot(partialContext.req.headers["user-agent"] || ""); const ctx = { ...partialContext, renderOpts: { ...this.renderOpts, supportsDynamicHTML: !isBotRequest } }; const payload = await fn(ctx); if (payload === null) { return; } const { req , res } = ctx; const { body , type , revalidateOptions } = payload; if (!res.sent) { const { generateEtags , poweredByHeader , dev } = this.renderOpts; if (dev) { // In dev, we should not cache pages for any reason. res.setHeader("Cache-Control", "no-store, must-revalidate"); } return this.sendRenderResult(req, res, { result: body, type, generateEtags, poweredByHeader, options: revalidateOptions }); } } async getStaticHTML(fn, partialContext) { const payload = await fn({ ...partialContext, renderOpts: { ...this.renderOpts, supportsDynamicHTML: false } }); if (payload === null) { return null; } return payload.body.toUnchunkedString(); } async render(req, res, pathname, query = {}, parsedUrl, internalRender = false) { var ref; if (!pathname.startsWith("/")) { console.warn(`Cannot render page with path "${pathname}", did you mean "/${pathname}"?. See more info here: https://nextjs.org/docs/messages/render-no-starting-slash`); } if (this.renderOpts.customServer && pathname === "/index" && !await this.hasPage("/index")) { // maintain backwards compatibility for custom server // (see custom-server integration tests) pathname = "/"; } // we allow custom servers to call render for all URLs // so check if we need to serve a static _next file or not. // we don't modify the URL for _next/data request but still // call render so we special case this to prevent an infinite loop if (!internalRender && !this.minimalMode && !query.__nextDataReq && (((ref = req.url) == null ? void 0 : ref.match(/^\/_next\//)) || this.hasStaticDir && req.url.match(/^\/static\//))) { return this.handleRequest(req, res, parsedUrl); } // Custom server users can run `app.render()` which needs compression. if (this.renderOpts.customServer) { this.handleCompression(req, res); } if ((0, _utils2).isBlockedPage(pathname)) { return this.render404(req, res, parsedUrl); } return this.pipe((ctx)=>this.renderToResponse(ctx), { req, res, pathname, query }); } async getStaticPaths(pathname) { // `staticPaths` is intentionally set to `undefined` as it should've // been caught when checking disk data. const staticPaths = undefined; // Read whether or not fallback should exist from the manifest. const fallbackField = this.getPrerenderManifest().dynamicRoutes[pathname].fallback; return { staticPaths, fallbackMode: typeof fallbackField === "string" ? "static" : fallbackField === null ? "blocking" : false }; } async renderToResponseWithComponents({ req , res , pathname , renderOpts: opts }, { components , query }) { var ref, ref5, ref6, ref7, ref8; const is404Page = pathname === "/404"; const is500Page = pathname === "/500"; const isLikeServerless = typeof components.ComponentMod === "object" && typeof components.ComponentMod.renderReqToHTML === "function"; const hasServerProps = !!components.getServerSideProps; const hasStaticPaths = !!components.getStaticPaths; const hasGetInitialProps = !!((ref = components.Component) == null ? void 0 : ref.getInitialProps); const isServerComponent = !!((ref5 = components.ComponentMod) == null ? void 0 : ref5.__next_rsc__); const isSSG = !!components.getStaticProps || // For static server component pages, we currently always consider them // as SSG since we also need to handle the next data (flight JSON). (isServerComponent && !hasServerProps && !hasGetInitialProps && process.env.NEXT_RUNTIME !== "edge"); // Toggle whether or not this is a Data request const isDataReq = !!query.__nextDataReq && (isSSG || hasServerProps || isServerComponent); delete query.__nextDataReq; // normalize req.url for SSG paths as it is not exposed // to getStaticProps and the asPath should not expose /_next/data if (isSSG && this.minimalMode && req.headers["x-matched-path"] && req.url.startsWith("/_next/data")) { req.url = this.stripNextDataPath(req.url); } if (!isServerComponent && !!req.headers["x-nextjs-data"] && (!res.statusCode || res.statusCode === 200)) { res.setHeader("x-nextjs-matched-path", `${query.__nextLocale ? `/${query.__nextLocale}` : ""}${pathname}`); } // Don't delete query.__flight__ yet, it still needs to be used in renderToHTML later const isFlightRequest = Boolean(this.serverComponentManifest && query.__flight__); // we need to ensure the status code if /404 is visited directly if (is404Page && !isDataReq && !isFlightRequest) { res.statusCode = 404; } // ensure correct status is set when visiting a status page // directly e.g. /500 if (_constants.STATIC_STATUS_PAGES.includes(pathname)) { res.statusCode = parseInt(pathname.slice(1), 10); } // static pages can only respond to GET/HEAD // requests so ensure we respond with 405 for // invalid requests if (!is404Page && !is500Page && pathname !== "/_error" && req.method !== "HEAD" && req.method !== "GET" && (typeof components.Component === "string" || isSSG)) { res.statusCode = 405; res.setHeader("Allow", [ "GET", "HEAD" ]); await this.renderError(null, req, res, pathname); return null; } // handle static page if (typeof components.Component === "string") { return { type: "html", // TODO: Static pages should be serialized as RenderResult body: _renderResult.default.fromStatic(components.Component) }; } if (!query.amp) { delete query.amp; } if (opts.supportsDynamicHTML === true) { var ref9; const isBotRequest = (0, _utils2).isBot(req.headers["user-agent"] || ""); const isSupportedDocument = typeof ((ref9 = components.Document) == null ? void 0 : ref9.getInitialProps) !== "function" || // When concurrent features is enabled, the built-in `Document` // component also supports dynamic HTML. (!!process.env.__NEXT_REACT_ROOT && _constants.NEXT_BUILTIN_DOCUMENT in components.Document); // Disable dynamic HTML in cases that we know it won't be generated, // so that we can continue generating a cache key when possible. opts.supportsDynamicHTML = !isSSG && !isLikeServerless && !isBotRequest && !query.amp && isSupportedDocument; } const defaultLocale = isSSG ? (ref6 = this.nextConfig.i18n) == null ? void 0 : ref6.defaultLocale : query.__nextDefaultLocale; const locale = query.__nextLocale; const locales = (ref7 = this.nextConfig.i18n) == null ? void 0 : ref7.locales; let previewData; let isPreviewMode = false; if (hasServerProps || isSSG) { // For the edge runtime, we don't support preview mode in SSG. if (process.env.NEXT_RUNTIME !== "edge") { const { tryGetPreviewData } = require("./api-utils/node"); previewData = tryGetPreviewData(req, res, this.renderOpts.previewProps); isPreviewMode = previewData !== false; } } let isManualRevalidate = false; let revalidateOnlyGenerated = false; if (isSSG) { ({ isManualRevalidate , revalidateOnlyGenerated } = (0, _apiUtils).checkIsManualRevalidate(req, this.renderOpts.previewProps)); } // Compute the iSSG cache key. We use the rewroteUrl since // pages with fallback: false are allowed to be rewritten to // and we need to look up the path by the rewritten path let urlPathname = (0, _url).parse(req.url || "").pathname || "/"; let resolvedUrlPathname = (0, _requestMeta).getRequestMeta(req, "_nextRewroteUrl") || urlPathname; if (isSSG && this.minimalMode && req.headers["x-matched-path"]) { // the url value is already correct when the matched-path header is set resolvedUrlPathname = urlPathname; } urlPathname = (0, _removeTrailingSlash).removeTrailingSlash(urlPathname); resolvedUrlPathname = (0, _normalizeLocalePath).normalizeLocalePath((0, _removeTrailingSlash).removeTrailingSlash(resolvedUrlPathname), (ref8 = this.nextConfig.i18n) == null ? void 0 : ref8.locales).pathname; const handleRedirect = (pageData)=>{ const redirect = { destination: pageData.pageProps.__N_REDIRECT, statusCode: pageData.pageProps.__N_REDIRECT_STATUS, basePath: pageData.pageProps.__N_REDIRECT_BASE_PATH }; const statusCode = (0, _redirectStatus).getRedirectStatus(redirect); const { basePath } = this.nextConfig; if (basePath && redirect.basePath !== false && redirect.destination.startsWith("/")) { redirect.destination = `${basePath}${redirect.destination}`; } if (redirect.destination.startsWith("/")) { redirect.destination = (0, _utils).normalizeRepeatedSlashes(redirect.destination); } res.redirect(redirect.destination, statusCode).body(redirect.destination).send(); }; // remove /_next/data prefix from urlPathname so it matches // for direct page visit and /_next/data visit if (isDataReq) { resolvedUrlPathname = this.stripNextDataPath(resolvedUrlPathname); urlPathname = this.stripNextDataPath(urlPathname); } let ssgCacheKey = isPreviewMode || !isSSG || opts.supportsDynamicHTML || isFlightRequest ? null // Preview mode, manual revalidate, flight request can bypass the cache : `${locale ? `/${locale}` : ""}${(pathname === "/" || resolvedUrlPathname === "/") && locale ? "" : resolvedUrlPathname}${query.amp ? ".amp" : ""}`; if ((is404Page || is500Page) && isSSG) { ssgCacheKey = `${locale ? `/${locale}` : ""}${pathname}${query.amp ? ".amp" : ""}`; } if (ssgCacheKey) { // we only encode path delimiters for path segments from // getStaticPaths so we need to attempt decoding the URL // to match against and only escape the path delimiters // this allows non-ascii values to be handled e.g. Japanese characters // TODO: investigate adding this handling for non-SSG pages so // non-ascii names work there also ssgCacheKey = ssgCacheKey.split("/").map((seg)=>{ try { seg = (0, _escapePathDelimiters).default(decodeURIComponent(seg), true); } catch (_) { // An improperly encoded URL was provided throw new _utils.DecodeError("failed to decode param"); } return seg; }).join("/"); // ensure /index and / is normalized to one key ssgCacheKey = ssgCacheKey === "/index" && pathname === "/" ? "/" : ssgCacheKey; } const doRender = async ()=>{ let pageData; let body; let sprRevalidate; let isNotFound; let isRedirect; // handle serverless if (isLikeServerless) { const renderResult = await components.ComponentMod.renderReqToHTML(req, res, "passthrough", { locale, locales, defaultLocale, optimizeCss: this.renderOpts.optimizeCss, nextScriptWorkers: this.renderOpts.nextScriptWorkers, distDir: this.distDir, fontManifest: this.renderOpts.fontManifest, domainLocales: this.renderOpts.domainLocales }); body = renderResult.html; pageData = renderResult.renderOpts.pageData; sprRevalidate = renderResult.renderOpts.revalidate; isNotFound = renderResult.renderOpts.isNotFound; isRedirect = renderResult.renderOpts.isRedirect; } else { const origQuery = (0, _url).parse(req.url || "", true).query; // clear any dynamic route params so they aren't in // the resolvedUrl if (opts.params) { Object.keys(opts.params).forEach((key)=>{ delete origQuery[key]; }); } const hadTrailingSlash = urlPathname !== "/" && this.nextConfig.trailingSlash; const resolvedUrl = (0, _url).format({ pathname: `${resolvedUrlPathname}${hadTrailingSlash ? "/" : ""}`, // make sure to only add query values from original URL query: origQuery }); const renderOpts = { ...components, ...opts, isDataReq, resolvedUrl, locale, locales, defaultLocale, // For getServerSideProps and getInitialProps we need to ensure we use the original URL // and not the resolved URL to prevent a hydration mismatch on // asPath resolvedAsPath: hasServerProps || hasGetInitialProps ? (0, _url).format({ // we use the original URL pathname less the _next/data prefix if // present pathname: `${urlPathname}${hadTrailingSlash ? "/" : ""}`, query: origQuery }) : resolvedUrl }; const renderResult = await this.renderHTML(req, res, pathname, query, renderOpts); body = renderResult; // TODO: change this to a different passing mechanism pageData = renderOpts.pageData; sprRevalidate = renderOpts.revalidate; isNotFound = renderOpts.isNotFound; isRedirect = renderOpts.isRedirect; } let value; if (isNotFound) { value = null; } else if (isRedirect) { value = { kind: "REDIRECT", props: pageData }; } else { if (!body) { return null; } value = { kind: "PAGE", html: body, pageData }; } return { revalidate: sprRevalidate, value }; }; const cacheEntry = await this.responseCache.get(ssgCacheKey, async (hasResolved, hadCache)=>{ const isProduction = !this.renderOpts.dev; const isDynamicPathname = (0, _utils1).isDynamicRoute(pathname); const didRespond = hasResolved || res.sent; let { staticPaths , fallbackMode } = hasStaticPaths ? await this.getStaticPaths(pathname) : { staticPaths: undefined, fallbackMode: false }; if (fallbackMode === "static" && (0, _utils2).isBot(req.headers["user-agent"] || "")) { fallbackMode = "blocking"; } // skip manual revalidate if cache is not present and // revalidate-if-generated is set if (isManualRevalidate && revalidateOnlyGenerated && !hadCache && !this.minimalMode) { await this.render404(req, res); return null; } // only allow manual revalidate for fallback: true/blocking // or for prerendered fallback: false paths if (isManualRevalidate && (fallbackMode !== false || hadCache)) { fallbackMode = "blocking"; } // When we did not respond from cache, we need to choose to block on // rendering or return a skeleton. // // * Data requests always block. // // * Blocking mode fallback always blocks. // // * Preview mode toggles all pages to be resolved in a blocking manner. // // * Non-dynamic pages should block (though this is an impossible // case in production). // // * Dynamic pages should return their skeleton if not defined in // getStaticPaths, then finish the data request on the client-side. // if (this.minimalMode !== true && fallbackMode !== "blocking" && ssgCacheKey && !didRespond && !isPreviewMode && isDynamicPathname && // Development should trigger fallback when the path is not in // `getStaticPaths` (isProduction || !staticPaths || !staticPaths.includes(// we use ssgCacheKey here as it is normalized to match the // encoding from getStaticPaths along with including the locale query.amp ? ssgCacheKey.replace(/\.amp$/, "") : ssgCacheKey))) { if (// In development, fall through to render to handle missing // getStaticPaths. (isProduction || staticPaths) && // When fallback isn't present, abort this render so we 404 fallbackMode !== "static") { throw new NoFallbackError(); } if (!isDataReq) {