Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions integration/tests/middleware-placement.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,36 @@
import { expect, test } from '@playwright/test';
import path from 'path';

import type { Application } from '../models/application';
import { stateFile } from '../models/stateFile';
import { appConfigs } from '../presets';
import { fs } from '../scripts';
import { createTestUtils } from '../testUtils';

function parseSemverMajor(range?: string): number | undefined {
if (!range) {
return undefined;
}
const match = String(range).match(/\d+/);
return match ? Number.parseInt(match[0], 10) : undefined;
}

async function detectNext(app: Application): Promise<{ isNext: boolean; version?: string }> {
// app.appDir exists for normal Application; for long-running apps, read it from the state file by serverUrl
const appDir =
(app as any).appDir ||
Object.values(stateFile.getLongRunningApps() || {}).find(a => a.serverUrl === app.serverUrl)?.appDir;

if (!appDir) {
return { isNext: false };
}

const pkg = await fs.readJSON(path.join(appDir, 'package.json'));
const nextRange: string | undefined = pkg.dependencies?.next || pkg.devDependencies?.next;

return { isNext: Boolean(nextRange), version: nextRange };
}
Comment on lines +18 to +32
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Add error handling and avoid any type cast.

The function has two concerns:

  1. Line 21: Using (app as any).appDir violates the coding guideline to avoid any types. Consider:

    • Adding appDir to the Application type if it's a valid property
    • Using a type guard or checking if the property exists with proper typing
    • Using as unknown as { appDir?: string } as a safer intermediate cast
  2. Line 28: fs.readJSON() has no error handling. If package.json is missing or malformed, the test will fail with an unclear error. Consider wrapping in try-catch and returning { isNext: false } on error.

Apply this diff to improve error handling:

 async function detectNext(app: Application): Promise<{ isNext: boolean; version?: string }> {
   // app.appDir exists for normal Application; for long-running apps, read it from the state file by serverUrl
   const appDir =
     (app as any).appDir ||
     Object.values(stateFile.getLongRunningApps() || {}).find(a => a.serverUrl === app.serverUrl)?.appDir;
 
   if (!appDir) {
     return { isNext: false };
   }
 
+  try {
     const pkg = await fs.readJSON(path.join(appDir, 'package.json'));
     const nextRange: string | undefined = pkg.dependencies?.next || pkg.devDependencies?.next;
 
     return { isNext: Boolean(nextRange), version: nextRange };
+  } catch {
+    return { isNext: false };
+  }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async function detectNext(app: Application): Promise<{ isNext: boolean; version?: string }> {
// app.appDir exists for normal Application; for long-running apps, read it from the state file by serverUrl
const appDir =
(app as any).appDir ||
Object.values(stateFile.getLongRunningApps() || {}).find(a => a.serverUrl === app.serverUrl)?.appDir;
if (!appDir) {
return { isNext: false };
}
const pkg = await fs.readJSON(path.join(appDir, 'package.json'));
const nextRange: string | undefined = pkg.dependencies?.next || pkg.devDependencies?.next;
return { isNext: Boolean(nextRange), version: nextRange };
}
async function detectNext(app: Application): Promise<{ isNext: boolean; version?: string }> {
// app.appDir exists for normal Application; for long-running apps, read it from the state file by serverUrl
const appDir =
(app as any).appDir ||
Object.values(stateFile.getLongRunningApps() || {}).find(a => a.serverUrl === app.serverUrl)?.appDir;
if (!appDir) {
return { isNext: false };
}
try {
const pkg = await fs.readJSON(path.join(appDir, 'package.json'));
const nextRange: string | undefined = pkg.dependencies?.next || pkg.devDependencies?.next;
return { isNext: Boolean(nextRange), version: nextRange };
} catch {
return { isNext: false };
}
}
🤖 Prompt for AI Agents
In integration/tests/middleware-placement.test.ts around lines 18 to 32, avoid
the unsafe (app as any).appDir cast and add error handling for fs.readJSON():
replace the any cast by either extending the Application type to include
optional appDir or use a narrow type-guard/safer intermediate cast (e.g. as
unknown as { appDir?: string }) before reading appDir, then wrap the
fs.readJSON(path.join(appDir, 'package.json')) call in a try-catch and return {
isNext: false } if reading/parsing fails so missing or malformed package.json
doesn’t crash the test.


const middlewareFileContents = `
import { clerkMiddleware } from '@clerk/nextjs/server';
export default clerkMiddleware();
Expand Down Expand Up @@ -61,6 +88,9 @@ test.describe('next start - invalid middleware at root on src/ @quickstart', ()
page,
context,
}) => {
const { version } = await detectNext(app);
const major = parseSemverMajor(version) ?? 0;
test.skip(major >= 16, 'Middleware detection is smarter in Next 16+.');
const u = createTestUtils({ app, page, context });
await u.page.goToAppHome();

Expand All @@ -69,6 +99,15 @@ test.describe('next start - invalid middleware at root on src/ @quickstart', ()
'Clerk: clerkMiddleware() was not run, your middleware file might be misplaced. Move your middleware file to ./src/middleware.ts. Currently located at ./middleware.ts',
);
});

test('Does not display misplaced middleware error on Next 16+', async ({ page, context }) => {
const { version } = await detectNext(app);
const major = parseSemverMajor(version) ?? 0;
test.skip(major < 16, 'Only applicable on Next 16+');
const u = createTestUtils({ app, page, context });
await u.page.goToAppHome();
expect(app.serveOutput).not.toContain('Clerk: clerkMiddleware() was not run');
});
});

test.describe('next start - invalid middleware inside app on src/ @quickstart', () => {
Expand Down
Loading