Unverified Commit 7fe01bb6 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Disable client-only for middleware and pages api layer (#55541)

We need to disable the default treat `middleware` and `pages/api` as
server-only, unless users explictly import "server-only" to poison it.

This will avoid the case that when a library is mixing "client-only" API
and shared components API in one bundle, and the shared API is used in
middleware or `pages/api` that might cause error. See the test case
added.

Follow up for #55394
parent e4439b14
...@@ -926,13 +926,13 @@ export default async function getBaseWebpackConfig( ...@@ -926,13 +926,13 @@ export default async function getBaseWebpackConfig(
: [] : []
const swcLoaderForMiddlewareLayer = useSWCLoader const swcLoaderForMiddlewareLayer = useSWCLoader
? getSwcLoader({ hasServerComponents: false, bundleTarget: 'server' }) ? getSwcLoader({ hasServerComponents: false, bundleTarget: 'default' })
: // When using Babel, we will have to use SWC to do the optimization : // When using Babel, we will have to use SWC to do the optimization
// for middleware to tree shake the unused default optimized imports like "next/server". // for middleware to tree shake the unused default optimized imports like "next/server".
// This will cause some performance overhead but // This will cause some performance overhead but
// acceptable as Babel will not be recommended. // acceptable as Babel will not be recommended.
[ [
getSwcLoader({ hasServerComponents: false, bundleTarget: 'server' }), getSwcLoader({ hasServerComponents: false, bundleTarget: 'default' }),
getBabelLoader(), getBabelLoader(),
] ]
...@@ -980,7 +980,7 @@ export default async function getBaseWebpackConfig( ...@@ -980,7 +980,7 @@ export default async function getBaseWebpackConfig(
loader: 'next-swc-loader', loader: 'next-swc-loader',
options: { options: {
...getSwcLoader().options, ...getSwcLoader().options,
bundleTarget: 'server', bundleTarget: 'default',
hasServerComponents: false, hasServerComponents: false,
}, },
} }
...@@ -1965,6 +1965,7 @@ export default async function getBaseWebpackConfig( ...@@ -1965,6 +1965,7 @@ export default async function getBaseWebpackConfig(
'next-flight-action-entry-loader', 'next-flight-action-entry-loader',
'next-flight-client-module-loader', 'next-flight-client-module-loader',
'noop-loader', 'noop-loader',
'empty-loader',
'next-middleware-loader', 'next-middleware-loader',
'next-edge-function-loader', 'next-edge-function-loader',
'next-edge-app-route-loader', 'next-edge-app-route-loader',
...@@ -2041,7 +2042,10 @@ export default async function getBaseWebpackConfig( ...@@ -2041,7 +2042,10 @@ export default async function getBaseWebpackConfig(
// Alias server-only and client-only to proper exports based on bundling layers // Alias server-only and client-only to proper exports based on bundling layers
{ {
issuerLayer: { issuerLayer: {
or: WEBPACK_LAYERS.GROUP.serverTarget, or: [
...WEBPACK_LAYERS.GROUP.server,
...WEBPACK_LAYERS.GROUP.nonClientServerTarget,
],
}, },
resolve: { resolve: {
// Error on client-only but allow server-only // Error on client-only but allow server-only
...@@ -2050,12 +2054,17 @@ export default async function getBaseWebpackConfig( ...@@ -2050,12 +2054,17 @@ export default async function getBaseWebpackConfig(
'client-only$': 'next/dist/compiled/client-only/error', 'client-only$': 'next/dist/compiled/client-only/error',
'next/dist/compiled/server-only$': 'next/dist/compiled/server-only$':
'next/dist/compiled/server-only/empty', 'next/dist/compiled/server-only/empty',
'next/dist/compiled/client-only$':
'next/dist/compiled/client-only/error',
}, },
}, },
}, },
{ {
issuerLayer: { issuerLayer: {
not: WEBPACK_LAYERS.GROUP.serverTarget, not: [
...WEBPACK_LAYERS.GROUP.server,
...WEBPACK_LAYERS.GROUP.nonClientServerTarget,
],
}, },
resolve: { resolve: {
// Error on server-only but allow client-only // Error on server-only but allow client-only
...@@ -2077,7 +2086,7 @@ export default async function getBaseWebpackConfig( ...@@ -2077,7 +2086,7 @@ export default async function getBaseWebpackConfig(
], ],
loader: 'next-invalid-import-error-loader', loader: 'next-invalid-import-error-loader',
issuerLayer: { issuerLayer: {
or: WEBPACK_LAYERS.GROUP.serverTarget, or: WEBPACK_LAYERS.GROUP.server,
}, },
options: { options: {
message: message:
...@@ -2091,13 +2100,29 @@ export default async function getBaseWebpackConfig( ...@@ -2091,13 +2100,29 @@ export default async function getBaseWebpackConfig(
], ],
loader: 'next-invalid-import-error-loader', loader: 'next-invalid-import-error-loader',
issuerLayer: { issuerLayer: {
not: WEBPACK_LAYERS.GROUP.serverTarget, not: [
...WEBPACK_LAYERS.GROUP.server,
...WEBPACK_LAYERS.GROUP.nonClientServerTarget,
],
}, },
options: { options: {
message: message:
"'server-only' cannot be imported from a Client Component module. It should only be used from a Server Component.", "'server-only' cannot be imported from a Client Component module. It should only be used from a Server Component.",
}, },
}, },
// Potential the bundle introduced into middleware and api can be poisoned by client-only
// but not being used, so we disabled the `client-only` erroring on these layers.
// `server-only` is still available.
{
test: [
/^client-only$/,
/next[\\/]dist[\\/]compiled[\\/]client-only[\\/]error/,
],
loader: 'empty-loader',
issuerLayer: {
or: WEBPACK_LAYERS.GROUP.nonClientServerTarget,
},
},
...(hasAppDir ...(hasAppDir
? [ ? [
{ {
......
import type { webpack } from 'next/dist/compiled/webpack/webpack'
const EmptyLoader: webpack.LoaderDefinitionFunction = () => 'export default {}'
export default EmptyLoader
...@@ -152,12 +152,7 @@ const WEBPACK_LAYERS = { ...@@ -152,12 +152,7 @@ const WEBPACK_LAYERS = {
WEBPACK_LAYERS_NAMES.appMetadataRoute, WEBPACK_LAYERS_NAMES.appMetadataRoute,
WEBPACK_LAYERS_NAMES.appRouteHandler, WEBPACK_LAYERS_NAMES.appRouteHandler,
], ],
serverTarget: [ nonClientServerTarget: [
// all GROUP.server
WEBPACK_LAYERS_NAMES.reactServerComponents,
WEBPACK_LAYERS_NAMES.actionBrowser,
WEBPACK_LAYERS_NAMES.appMetadataRoute,
WEBPACK_LAYERS_NAMES.appRouteHandler,
// plus middleware and pages api // plus middleware and pages api
WEBPACK_LAYERS_NAMES.middleware, WEBPACK_LAYERS_NAMES.middleware,
WEBPACK_LAYERS_NAMES.api, WEBPACK_LAYERS_NAMES.api,
......
...@@ -6,55 +6,99 @@ createNextDescribe( ...@@ -6,55 +6,99 @@ createNextDescribe(
files: __dirname, files: __dirname,
}, },
({ next, isNextStart }) => { ({ next, isNextStart }) => {
it('should render routes marked with restriction marks without errors', async () => { function runTests() {
const routes = [ it('should render routes marked with restriction marks without errors', async () => {
// app client components pages const routes = [
'/app/client', // app client components pages
'/app/client-edge', '/app/client',
// app sever components pages
'/app/server',
'/app/server-edge',
// app routes
'/app/route',
'/app/route-edge',
// pages/api
'/api/hello',
'/api/hello-edge',
]
for (const route of routes) {
const { status } = await next.fetch(route)
expect([route, status]).toEqual([route, 200])
}
})
if (isNextStart) {
it('should log the build info properly', async () => {
const cliOutput = next.cliOutput
expect(cliOutput).toContain('Middleware')
const functionsManifest = JSON.parse(
await next.readFile('.next/server/functions-config-manifest.json')
)
expect(functionsManifest.functions).toContainKeys([
'/app/route-edge',
'/api/hello-edge',
'/app/client-edge', '/app/client-edge',
// app sever components pages
'/app/server',
'/app/server-edge', '/app/server-edge',
]) // app routes
const pagesManifest = JSON.parse( '/app/route',
await next.readFile('.next/server/pages-manifest.json') '/app/route-edge',
) // pages/api
const middlewareManifest = JSON.parse(
await next.readFile('.next/server/middleware-manifest.json')
)
expect(middlewareManifest.middleware).toBeTruthy()
expect(pagesManifest).toContainKeys([
'/api/hello-edge',
'/pages-ssr',
'/api/hello', '/api/hello',
]) '/api/hello-edge',
'/api/mixed',
]
for (const route of routes) {
const { status } = await next.fetch(route)
expect([route, status]).toEqual([route, 200])
}
}) })
if (isNextStart) {
it('should log the build info properly', async () => {
const cliOutput = next.cliOutput
expect(cliOutput).toContain('Middleware')
const functionsManifest = JSON.parse(
await next.readFile('.next/server/functions-config-manifest.json')
)
expect(functionsManifest.functions).toContainKeys([
'/app/route-edge',
'/api/hello-edge',
'/app/client-edge',
'/app/server-edge',
])
const pagesManifest = JSON.parse(
await next.readFile('.next/server/pages-manifest.json')
)
const middlewareManifest = JSON.parse(
await next.readFile('.next/server/middleware-manifest.json')
)
expect(middlewareManifest.middleware).toBeTruthy()
expect(pagesManifest).toContainKeys([
'/api/hello-edge',
'/pages-ssr',
'/api/hello',
])
})
}
} }
describe('no server-only in server targets', () => {
const middlewareFile = 'middleware.js'
// const pagesApiFile = 'pages/api/hello.js'
let middlewareContent = ''
// let pagesApiContent = ''
beforeAll(async () => {
await next.stop()
middlewareContent = await next.readFile(middlewareFile)
// pagesApiContent = await next.readFile(pagesApiFile)
await next.patchFile(
middlewareFile,
middlewareContent
.replace("import 'server-only'", "// import 'server-only'")
.replace("// import './lib/mixed-lib'", "import './lib/mixed-lib'")
)
// await next.patchFile(
// pagesApiFile,
// pagesApiContent
// .replace("import 'server-only'", "// import 'server-only'")
// .replace(
// "// import '../../lib/mixed-lib'",
// "import '../../lib/mixed-lib'"
// )
// )
await next.start()
})
afterAll(async () => {
await next.patchFile(middlewareFile, middlewareContent)
// await next.patchFile(pagesApiFile, pagesApiContent)
})
runTests()
})
describe('with server-only in server targets', () => {
runTests()
})
} }
) )
import 'client-only'
export const client = 'client:module'
export { shared as sharedComponentValue } from './shared'
// export but won't be consumed in the test
export { client as clientComponentValue } from './client'
export const shared = 'shared:module'
import 'server-only' import 'server-only'
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
// import './lib/mixed-lib'
export function middleware() { export function middleware(request) {
return NextResponse.next() return NextResponse.next()
} }
import 'server-only' import 'server-only'
export default function handler() { export default function handler() {
return new Response('api/hello-edge.js') return new Response('pages/api/hello-edge.js:')
} }
export const runtime = 'edge' export const runtime = 'edge'
import 'server-only' import 'server-only'
export default function handler(req, res) { export default function handler(req, res) {
return res.send('api/hello.js') return res.send('pages/api/hello.js:')
} }
import '../../lib/mixed-lib'
export default function handler(req, res) {
return res.send('pages/api/mixed.js:')
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment