MCPcopy
hub / github.com/vitejs/vite / baseMiddleware

Function baseMiddleware

packages/vite/src/node/server/middlewares/base.ts:7–62  ·  view source on GitHub ↗
(
  rawBase: string,
  middlewareMode: boolean,
)

Source from the content-addressed store, hash-verified

5// this middleware is only active when (base !== '/')
6
7export function baseMiddleware(
8 rawBase: string,
9 middlewareMode: boolean,
10): Connect.NextHandleFunction {
11 // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
12 return function viteBaseMiddleware(req, res, next) {
13 const url = req.url!
14 const pathname = cleanUrl(url)
15 const base = rawBase
16
17 if (pathname.startsWith(base)) {
18 // rewrite url to remove base. this ensures that other middleware does
19 // not need to consider base being prepended or not
20 req.url = stripBase(url, base)
21 return next()
22 }
23
24 // skip redirect and error fallback on middleware mode, #4057
25 if (middlewareMode) {
26 return next()
27 }
28
29 if (pathname === '/' || pathname === '/index.html') {
30 // redirect root visit to based url with search and hash
31 res.writeHead(302, {
32 Location: base + url.slice(pathname.length),
33 })
34 res.end()
35 return
36 }
37
38 // non-based page visit
39 const redirectPath =
40 withTrailingSlash(url) !== base ? joinUrlSegments(base, url) : base
41 if (req.headers.accept?.includes('text/html')) {
42 res.writeHead(404, {
43 'Content-Type': 'text/html',
44 })
45 res.end(
46 `The server is configured with a public base URL of ${base} - ` +
47 `did you mean to visit <a href="${redirectPath}">${redirectPath}</a> instead?`,
48 )
49 return
50 } else {
51 // not found for resources
52 res.writeHead(404, {
53 'Content-Type': 'text/plain',
54 })
55 res.end(
56 `The server is configured with a public base URL of ${base} - ` +
57 `did you mean to visit ${redirectPath} instead?`,
58 )
59 return
60 }
61 }
62}

Callers 2

previewFunction · 0.90
_createServerFunction · 0.90

Calls 5

cleanUrlFunction · 0.90
stripBaseFunction · 0.90
withTrailingSlashFunction · 0.90
joinUrlSegmentsFunction · 0.90
nextFunction · 0.85

Tested by

no test coverage detected