Skip to content

Commit

Permalink
Throw an error when target: 'serverless' is used with Middleware (#…
Browse files Browse the repository at this point in the history
…37819)

Serverless target is deprecated, so we don't support it in Middleware as it's a new feature,
but we need to have a good error message for that. This commit solves that.

## Related

* Fixes #37433



## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`
  • Loading branch information
Schniz committed Jun 19, 2022
1 parent 8577c4f commit e05c31d
Show file tree
Hide file tree
Showing 6 changed files with 39 additions and 0 deletions.
5 changes: 5 additions & 0 deletions packages/next/build/entries.ts
Expand Up @@ -31,6 +31,7 @@ import {
isMiddlewareFilename,
isServerComponentPage,
NestedMiddlewareError,
MiddlewareInServerlessTargetError,
} from './utils'
import { getPageStaticInfo } from './analysis/get-page-static-info'
import { normalizePathSep } from '../shared/lib/page-path/normalize-path-sep'
Expand Down Expand Up @@ -348,6 +349,10 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {

if (isMiddlewareFile(page)) {
middlewareRegex = staticInfo.middleware?.pathMatcher?.source || '.*'

if (target === 'serverless') {
throw new MiddlewareInServerlessTargetError()
}
}

runDependingOnPageType({
Expand Down
11 changes: 11 additions & 0 deletions packages/next/build/utils.ts
Expand Up @@ -1331,6 +1331,17 @@ export function getPossibleMiddlewareFilenames(
path.join(folder, `${MIDDLEWARE_FILENAME}.${extension}`)
)
}

export class MiddlewareInServerlessTargetError extends Error {
constructor() {
super(
'Next.js Middleware is not supported in the deprecated serverless target.\n' +
'Please remove `target: "serverless" from your next.config.js to use Middleware.'
)
this.name = 'MiddlewareInServerlessTargetError'
}
}

export class NestedMiddlewareError extends Error {
constructor(nestedFileNames: string[], mainDir: string, pagesDir: string) {
super(
Expand Down
@@ -0,0 +1,3 @@
export default (req) => {
console.log(req.url)
}
@@ -0,0 +1,3 @@
module.exports = {
target: 'serverless',
}
@@ -0,0 +1,3 @@
export default function Home() {
return <div>Hello</div>
}
@@ -0,0 +1,14 @@
import { nextBuild } from 'next-test-utils'
import path from 'path'

describe('Middleware is not allowed when using serverless target', () => {
it('fails to build', async () => {
const { code, stderr } = await nextBuild(
path.resolve(__dirname, './app'),
undefined,
{ ignoreFail: true, stderr: true }
)
expect(code).toEqual(1)
expect(stderr).toContain('MiddlewareInServerlessTargetError')
})
})

0 comments on commit e05c31d

Please sign in to comment.