Skip to content

Pass logger from req#934

Merged
elie222 merged 4 commits intomainfrom
feat/logger-api
Nov 9, 2025
Merged

Pass logger from req#934
elie222 merged 4 commits intomainfrom
feat/logger-api

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Nov 9, 2025

Summary by CodeRabbit

  • Refactor
    • Introduced per-request scoped logging and enriched request context for improved traceability and error routing.
    • Updated middleware to attach, propagate and flush request loggers across authentication and email flows.
  • New Features
    • Added an asynchronous flush capability to all logger variants.
    • Middleware supports optional scope-based invocation for richer telemetry.
  • Tests
    • Test setup runs after-hooks synchronously and removed local logger mocks.

@vercel
Copy link

vercel bot commented Nov 9, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Updated (UTC)
inbox-zero Ready Ready Preview Nov 9, 2025 10:02pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 9, 2025

Caution

Review failed

The pull request is closed.

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Per-request logging was introduced and threaded through middleware and route handlers; logger implementations received a uniform async flush() method; route handlers were updated to accept a scoped middleware identifier and use req.logger; tests removed module-level logger mocks and vitest now loads a setup file stubbing next/server.after().

Changes

Cohort / File(s) Summary
Route handler update
apps/web/app/api/ai/models/route.ts
GET updated from withEmailAccount(handler) to withEmailAccount("api/ai/models", handler); inner handler param renamed requestreq; reads req.auth.emailAccountId; removed module-scoped logger import and switched to req.logger.
Logger infrastructure
apps/web/utils/logger.ts
Added flush(): Promise<void> to all logger variants (console, Axiom, null) to provide a uniform async flush API.
Middleware & request types
apps/web/utils/middleware.ts
Added RequestWithLogger and updated RequestWithAuth / RequestWithEmailAccount to include logger; withMiddleware accepts optional scope and attaches per-request logger; schedules flush via next/server.after; added getLogger() / flushLogger() helpers; added overloads for withError, withAuth, withEmailAccount, withEmailProvider.
Tests: logger mocks removed
apps/web/__tests__/ai-detect-recurring-pattern.test.ts, apps/web/app/api/sso/signin/route.test.ts, apps/web/utils/auth.test.ts, apps/web/utils/cron.test.ts, apps/web/utils/encryption.test.ts
Removed vi.mock("@/utils/logger", ...) from multiple tests; tests now rely on global/test-setup behavior or per-request logger.
Test bootstrap
apps/web/__tests__/setup.ts, apps/web/vitest.config.mts
Added __tests__/setup.ts that stubs next/server.after() to run callbacks synchronously; registered the setup file in vitest.config.mts via setupFiles.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant M as withMiddleware
    participant H as Route Handler
    participant L as req.logger
    participant A as next/server.after()

    C->>M: HTTP request
    M->>M: init per-request logger (x-request-id, URL, auth)
    M->>H: call handler with enriched req
    H->>L: log actions / errors via req.logger
    H-->>M: return response
    M->>A: schedule flush callback
    A->>L: flush()
    A-->>C: finalize response

    alt Error path
        H->>L: log error
        M->>A: schedule flush on error
        A->>L: flush()
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Pay attention to type changes for RequestWithLogger and propagation into middleware overloads.
  • Verify correct initialization and enrichment of per-request logger context (x-request-id, auth/email/account fields).
  • Confirm next/server.after usage and that flush() is called in all success/error paths.
  • Review updated routes for correct usage of withEmailAccount(scope, handler) and req naming.

Possibly related PRs

  • Handle errors better #848 — coordinated refactor moving module-level loggers to request-scoped req.logger across middleware and handlers.
  • Timezone calendar #812 — changes to apps/web/utils/logger.ts and logger API; overlaps with the added flush() behavior.
  • Extend logger functionality #331 — earlier modifications to the logging subsystem and scoped/request logger adoption; touches the same logging surfaces.

Suggested reviewers

  • anakarentorosserrano-star

Poem

🐇
I stitched a logger small and bright,
Each request a lantern in the night,
I flush the stories, neat and quick,
Hops of logs — concise and slick,
A rabbit’s cheer for scoped delight! 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: refactoring to pass logger from request object (req) instead of using module-level loggers throughout the codebase.

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0967b95 and 0e66fda.

📒 Files selected for processing (2)
  • apps/web/__tests__/setup.ts (1 hunks)
  • apps/web/utils/middleware.ts (14 hunks)

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fac8ca3 and 0eef552.

📒 Files selected for processing (3)
  • apps/web/app/api/ai/models/route.ts (2 hunks)
  • apps/web/utils/logger.ts (3 hunks)
  • apps/web/utils/middleware.ts (14 hunks)
🧰 Additional context used
📓 Path-based instructions (12)
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Path aliases: Use @/ for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Leverage TypeScript inference for better DX

Files:

  • apps/web/utils/logger.ts
  • apps/web/app/api/ai/models/route.ts
  • apps/web/utils/middleware.ts
!{.cursor/rules/*.mdc}

📄 CodeRabbit inference engine (.cursor/rules/cursor-rules.mdc)

Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location

Files:

  • apps/web/utils/logger.ts
  • apps/web/app/api/ai/models/route.ts
  • apps/web/utils/middleware.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)

**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod

Files:

  • apps/web/utils/logger.ts
  • apps/web/app/api/ai/models/route.ts
  • apps/web/utils/middleware.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)

**/*.{ts,tsx}: Use createScopedLogger for logging in backend TypeScript files
Typically add the logger initialization at the top of the file when using createScopedLogger
Only use .with() on a logger instance within a specific function, not for a global logger

Import Prisma in the project using import prisma from "@/utils/prisma";

**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.

Files:

  • apps/web/utils/logger.ts
  • apps/web/app/api/ai/models/route.ts
  • apps/web/utils/middleware.ts
apps/web/utils/**

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

Create utility functions in utils/ folder for reusable logic

Files:

  • apps/web/utils/logger.ts
  • apps/web/utils/middleware.ts
apps/web/utils/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

apps/web/utils/**/*.ts: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size

Files:

  • apps/web/utils/logger.ts
  • apps/web/utils/middleware.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use elements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...

Files:

  • apps/web/utils/logger.ts
  • apps/web/app/api/ai/models/route.ts
  • apps/web/utils/middleware.ts
!pages/_document.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.

Files:

  • apps/web/utils/logger.ts
  • apps/web/app/api/ai/models/route.ts
  • apps/web/utils/middleware.ts
apps/web/app/**

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

NextJS app router structure with (app) directory

Files:

  • apps/web/app/api/ai/models/route.ts
apps/web/app/api/**/route.ts

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/app/api/**/route.ts: Use withAuth for user-level operations
Use withEmailAccount for email-account-level operations
Do NOT use POST API routes for mutations - use server actions instead
No need for try/catch in GET routes when using middleware
Export response types from GET routes

apps/web/app/api/**/route.ts: Wrap all GET API route handlers with withAuth or withEmailAccount middleware for authentication and authorization.
Export response types from GET API routes for type-safe client usage.
Do not use try/catch in GET API routes when using authentication middleware; rely on centralized error handling.

Files:

  • apps/web/app/api/ai/models/route.ts
**/api/**/route.ts

📄 CodeRabbit inference engine (.cursor/rules/security.mdc)

**/api/**/route.ts: ALL API routes that handle user data MUST use appropriate authentication and authorization middleware (withAuth or withEmailAccount).
ALL database queries in API routes MUST be scoped to the authenticated user/account (e.g., include userId or emailAccountId in query filters).
Always validate that resources belong to the authenticated user before performing operations (resource ownership validation).
Use withEmailAccount middleware for API routes that operate on a specific email account (i.e., use or require emailAccountId).
Use withAuth middleware for API routes that operate at the user level (i.e., use or require only userId).
Use withError middleware (with proper validation) for public endpoints, custom authentication, or cron endpoints.
Cron endpoints MUST use withError middleware and validate the cron secret using hasCronSecret(request) or hasPostCronSecret(request).
Cron endpoints MUST capture unauthorized attempts with captureException and return a 401 status for unauthorized requests.
All parameters in API routes MUST be validated for type, format, and length before use.
Request bodies in API routes MUST be validated using Zod schemas before use.
All Prisma queries in API routes MUST only return necessary fields and never expose sensitive data.
Error messages in API routes MUST not leak internal information or sensitive data; use generic error messages and SafeError where appropriate.
API routes MUST use a consistent error response format, returning JSON with an error message and status code.
All findUnique and findFirst Prisma calls in API routes MUST include ownership filters (e.g., userId or emailAccountId).
All findMany Prisma calls in API routes MUST be scoped to the authenticated user's data.
Never use direct object references in API routes without ownership checks (prevent IDOR vulnerabilities).
Prevent mass assignment vulnerabilities by only allowing explicitly whitelisted fields in update operations in AP...

Files:

  • apps/web/app/api/ai/models/route.ts
apps/web/app/api/**/*.{ts,js}

📄 CodeRabbit inference engine (.cursor/rules/security-audit.mdc)

apps/web/app/api/**/*.{ts,js}: All API route handlers in 'apps/web/app/api/' must use authentication middleware: withAuth, withEmailAccount, or withError (with custom authentication logic).
All Prisma queries in API routes must include user/account filtering (e.g., emailAccountId or userId in WHERE clauses) to prevent unauthorized data access.
All parameters used in API routes must be validated before use; do not use parameters from 'params' or request bodies directly in queries without validation.
Request bodies in API routes should use Zod schemas for validation.
API routes should only return necessary fields using Prisma's 'select' and must not include sensitive data in error messages.
Error messages in API routes must not reveal internal details; use generic errors and SafeError for user-facing errors.
All QStash endpoints (API routes called via publishToQstash or publishToQstashQueue) must use verifySignatureAppRouter to verify request authenticity.
All cron endpoints in API routes must use hasCronSecret or hasPostCronSecret for authentication.
Do not hardcode weak or plaintext secrets in API route files; secrets must not be directly assigned as string literals.
Review all new withError usage in API routes to ensure custom authentication is implemented where required.

Files:

  • apps/web/app/api/ai/models/route.ts
🧠 Learnings (28)
📚 Learning: 2025-09-17T22:05:28.646Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-09-17T22:05:28.646Z
Learning: Applies to apps/web/utils/ai/**/*.{ts,tsx} : Use descriptive scoped loggers for each feature

Applied to files:

  • apps/web/utils/logger.ts
  • apps/web/app/api/ai/models/route.ts
  • apps/web/utils/middleware.ts
📚 Learning: 2025-07-18T15:06:47.625Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/logging.mdc:0-0
Timestamp: 2025-07-18T15:06:47.625Z
Learning: Applies to **/*.{ts,tsx} : Typically add the logger initialization at the top of the file when using `createScopedLogger`

Applied to files:

  • apps/web/utils/logger.ts
  • apps/web/utils/middleware.ts
📚 Learning: 2025-07-18T15:06:47.625Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/logging.mdc:0-0
Timestamp: 2025-07-18T15:06:47.625Z
Learning: Applies to **/*.{ts,tsx} : Use `createScopedLogger` for logging in backend TypeScript files

Applied to files:

  • apps/web/utils/logger.ts
  • apps/web/utils/middleware.ts
📚 Learning: 2025-07-18T15:06:47.625Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/logging.mdc:0-0
Timestamp: 2025-07-18T15:06:47.625Z
Learning: Applies to **/*.{ts,tsx} : Only use `.with()` on a logger instance within a specific function, not for a global logger

Applied to files:

  • apps/web/utils/logger.ts
  • apps/web/utils/middleware.ts
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/app/api/**/route.ts : Use `withEmailAccount` for email-account-level operations

Applied to files:

  • apps/web/app/api/ai/models/route.ts
  • apps/web/utils/middleware.ts
📚 Learning: 2025-07-18T15:05:26.713Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-07-18T15:05:26.713Z
Learning: Applies to app/api/**/route.ts : Always wrap the handler with `withAuth` or `withEmailAccount` for consistent error handling and authentication in GET API routes.

Applied to files:

  • apps/web/app/api/ai/models/route.ts
  • apps/web/utils/middleware.ts
📚 Learning: 2025-07-18T15:05:16.146Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-07-18T15:05:16.146Z
Learning: Applies to apps/web/app/api/**/route.ts : Wrap all GET API route handlers with `withAuth` or `withEmailAccount` middleware for authentication and authorization.

Applied to files:

  • apps/web/app/api/ai/models/route.ts
📚 Learning: 2025-07-18T17:27:46.389Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-07-18T17:27:46.389Z
Learning: Applies to **/api/**/route.ts : Use `withEmailAccount` middleware for API routes that operate on a specific email account (i.e., use or require `emailAccountId`).

Applied to files:

  • apps/web/app/api/ai/models/route.ts
  • apps/web/utils/middleware.ts
📚 Learning: 2025-07-18T15:05:26.713Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-07-18T15:05:26.713Z
Learning: Applies to app/api/**/route.ts : Do not use try/catch in GET API route handlers, as `withAuth` and `withEmailAccount` handle error catching.

Applied to files:

  • apps/web/app/api/ai/models/route.ts
📚 Learning: 2025-07-20T09:00:41.968Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-07-20T09:00:41.968Z
Learning: Applies to apps/web/app/api/**/*.{ts,js} : All API route handlers in 'apps/web/app/api/' must use authentication middleware: withAuth, withEmailAccount, or withError (with custom authentication logic).

Applied to files:

  • apps/web/app/api/ai/models/route.ts
📚 Learning: 2025-07-18T17:27:46.389Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-07-18T17:27:46.389Z
Learning: Applies to **/api/**/route.ts : ALL API routes that handle user data MUST use appropriate authentication and authorization middleware (withAuth or withEmailAccount).

Applied to files:

  • apps/web/app/api/ai/models/route.ts
📚 Learning: 2025-07-20T09:00:41.968Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-07-20T09:00:41.968Z
Learning: Applies to apps/web/app/api/**/*.{ts,js} : Review all new withError usage in API routes to ensure custom authentication is implemented where required.

Applied to files:

  • apps/web/app/api/ai/models/route.ts
  • apps/web/utils/middleware.ts
📚 Learning: 2025-07-18T15:05:16.146Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-07-18T15:05:16.146Z
Learning: Applies to apps/web/app/api/**/route.ts : Do not use try/catch in GET API routes when using authentication middleware; rely on centralized error handling.

Applied to files:

  • apps/web/app/api/ai/models/route.ts
📚 Learning: 2025-07-18T17:27:46.389Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-07-18T17:27:46.389Z
Learning: Applies to **/api/**/route.ts : ALL database queries in API routes MUST be scoped to the authenticated user/account (e.g., include userId or emailAccountId in query filters).

Applied to files:

  • apps/web/app/api/ai/models/route.ts
📚 Learning: 2025-06-23T12:26:53.882Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/prisma.mdc:0-0
Timestamp: 2025-06-23T12:26:53.882Z
Learning: In this project, Prisma should be imported using 'import prisma from "@/utils/prisma";' in TypeScript files.

Applied to files:

  • apps/web/app/api/ai/models/route.ts
📚 Learning: 2025-07-20T09:00:41.968Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-07-20T09:00:41.968Z
Learning: Applies to apps/web/app/api/**/*.{ts,js} : All Prisma queries in API routes must include user/account filtering (e.g., emailAccountId or userId in WHERE clauses) to prevent unauthorized data access.

Applied to files:

  • apps/web/app/api/ai/models/route.ts
📚 Learning: 2025-09-17T22:05:28.646Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-09-17T22:05:28.646Z
Learning: Applies to apps/web/utils/ai/**/*.{ts,tsx} : Log inputs and outputs with appropriate log levels and include relevant context

Applied to files:

  • apps/web/utils/middleware.ts
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/utils/actions/**/*.ts : Use Zod schemas for validation on both client and server

Applied to files:

  • apps/web/utils/middleware.ts
📚 Learning: 2025-07-19T17:50:28.270Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/utilities.mdc:0-0
Timestamp: 2025-07-19T17:50:28.270Z
Learning: The `utils` folder also contains core app logic such as Next.js Server Actions and Gmail API requests.

Applied to files:

  • apps/web/utils/middleware.ts
📚 Learning: 2025-07-18T15:05:16.146Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-07-18T15:05:16.146Z
Learning: Applies to apps/web/utils/actions/*.validation.ts : Define Zod schemas for validation in dedicated files and use them for both client and server validation.

Applied to files:

  • apps/web/utils/middleware.ts
📚 Learning: 2025-07-18T17:27:58.249Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-07-18T17:27:58.249Z
Learning: Applies to apps/web/utils/actions/*.ts : Use `SafeError` for expected/handled errors within actions if needed. `next-safe-action` provides centralized error handling.

Applied to files:

  • apps/web/utils/middleware.ts
📚 Learning: 2025-07-18T17:27:58.249Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-07-18T17:27:58.249Z
Learning: Applies to apps/web/utils/actions/*.validation.ts : Define input validation schemas using Zod in the corresponding `.validation.ts` file. These schemas are used by `next-safe-action` (`.schema()`) and can also be reused on the client for form validation.

Applied to files:

  • apps/web/utils/middleware.ts
📚 Learning: 2025-07-20T09:00:41.968Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-07-20T09:00:41.968Z
Learning: Applies to apps/web/app/api/**/*.{ts,js} : Request bodies in API routes should use Zod schemas for validation.

Applied to files:

  • apps/web/utils/middleware.ts
📚 Learning: 2025-09-17T22:05:28.646Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-09-17T22:05:28.646Z
Learning: Applies to apps/web/utils/ai/**/*.{ts,tsx} : Always define a Zod schema for response validation

Applied to files:

  • apps/web/utils/middleware.ts
📚 Learning: 2025-07-18T17:27:58.249Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-07-18T17:27:58.249Z
Learning: Applies to apps/web/utils/actions/*.ts : Implement all server actions using the `next-safe-action` library for type safety, input validation, context management, and error handling. Refer to `apps/web/utils/actions/safe-action.ts` for client definitions (`actionClient`, `actionClientUser`, `adminActionClient`).

Applied to files:

  • apps/web/utils/middleware.ts
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/utils/actions/**/*.ts : `next-safe-action` provides centralized error handling

Applied to files:

  • apps/web/utils/middleware.ts
📚 Learning: 2025-07-18T17:27:58.249Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-07-18T17:27:58.249Z
Learning: Applies to apps/web/utils/actions/*.ts : Use `actionClient` when both authenticated user context and a specific `emailAccountId` are needed. The `emailAccountId` must be bound when calling the action from the client.

Applied to files:

  • apps/web/utils/middleware.ts
📚 Learning: 2025-07-18T17:27:46.389Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-07-18T17:27:46.389Z
Learning: Applies to **/api/**/route.ts : Use `withError` middleware (with proper validation) for public endpoints, custom authentication, or cron endpoints.

Applied to files:

  • apps/web/utils/middleware.ts
🧬 Code graph analysis (2)
apps/web/app/api/ai/models/route.ts (1)
apps/web/utils/middleware.ts (1)
  • withEmailAccount (374-392)
apps/web/utils/middleware.ts (1)
apps/web/utils/logger.ts (2)
  • Logger (5-5)
  • createScopedLogger (17-81)
🪛 GitHub Actions: Run Tests
apps/web/utils/middleware.ts

[error] 437-439: Runtime error: 'after' was called outside a request scope. This is caused by Next.js dynamic API wrong context in middleware tests. Triggered during test step 'pnpm -F inbox-zero-ai test'.

🪛 GitHub Check: test
apps/web/utils/middleware.ts

[failure] 437-437: utils/middleware.test.ts > Middleware > withEmailAccount > should return 403 if email account ID is invalid
Error: after was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context
❯ after ../../node_modules/.pnpm/next@15.5.6_@babel+core@7.28.5_@opentelemetry+api@1.9.0_react-dom@19.1.1_react@19.1.1/node_modules/next/src/server/after/after.ts:14:11
❯ flushLogger utils/middleware.ts:437:5
❯ utils/middleware.ts:93:7
❯ utils/middleware.test.ts:302:24

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: { __NEXT_ERROR_CODE: 'E468' }


[failure] 437-437: utils/middleware.test.ts > Middleware > withEmailAccount > should return 403 if email account header is missing
Error: after was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context
❯ after ../../node_modules/.pnpm/next@15.5.6_@babel+core@7.28.5_@opentelemetry+api@1.9.0_react-dom@19.1.1_react@19.1.1/node_modules/next/src/server/after/after.ts:14:11
❯ flushLogger utils/middleware.ts:437:5
❯ utils/middleware.ts:93:7
❯ utils/middleware.test.ts:271:24

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: { __NEXT_ERROR_CODE: 'E468' }


[failure] 437-437: utils/middleware.test.ts > Middleware > withEmailAccount > should call handler with email account info if header exists and account is valid
Error: after was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context
❯ after ../../node_modules/.pnpm/next@15.5.6_@babel+core@7.28.5_@opentelemetry+api@1.9.0_react-dom@19.1.1_react@19.1.1/node_modules/next/src/server/after/after.ts:14:11
❯ flushLogger utils/middleware.ts:437:5
❯ utils/middleware.ts:93:7
❯ utils/middleware.test.ts:239:7

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: { __NEXT_ERROR_CODE: 'E468' }


[failure] 437-437: utils/middleware.test.ts > Middleware > withAuth > should return 401 if session does not exist
Error: after was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context
❯ after ../../node_modules/.pnpm/next@15.5.6_@babel+core@7.28.5_@opentelemetry+api@1.9.0_react-dom@19.1.1_react@19.1.1/node_modules/next/src/server/after/after.ts:14:11
❯ flushLogger utils/middleware.ts:437:5
❯ utils/middleware.ts:93:7
❯ utils/middleware.test.ts:200:24

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: { __NEXT_ERROR_CODE: 'E468' }


[failure] 437-437: utils/middleware.test.ts > Middleware > withAuth > should call the handler with auth info if session exists
Error: after was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context
❯ after ../../node_modules/.pnpm/next@15.5.6_@babel+core@7.28.5_@opentelemetry+api@1.9.0_react-dom@19.1.1_react@19.1.1/node_modules/next/src/server/after/after.ts:14:11
❯ flushLogger utils/middleware.ts:437:5
❯ utils/middleware.ts:93:7
❯ utils/middleware.test.ts:184:7

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: { __NEXT_ERROR_CODE: 'E468' }


[failure] 437-437: utils/middleware.test.ts > Middleware > withError > should return 500 and capture unhandled errors
Error: after was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context
❯ after ../../node_modules/.pnpm/next@15.5.6_@babel+core@7.28.5_@opentelemetry+api@1.9.0_react-dom@19.1.1_react@19.1.1/node_modules/next/src/server/after/after.ts:14:11
❯ flushLogger utils/middleware.ts:437:5
❯ utils/middleware.ts:93:7
❯ utils/middleware.test.ts:160:24

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: { __NEXT_ERROR_CODE: 'E468' }


[failure] 437-437: utils/middleware.test.ts > Middleware > withError > should handle common errors using checkCommonErrors
Error: after was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context
❯ after ../../node_modules/.pnpm/next@15.5.6_@babel+core@7.28.5_@opentelemetry+api@1.9.0_react-dom@19.1.1_react@19.1.1/node_modules/next/src/server/after/after.ts:14:11
❯ flushLogger utils/middleware.ts:437:5
❯ utils/middleware.ts:93:7
❯ utils/middleware.test.ts:143:24

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: { __NEXT_ERROR_CODE: 'E468' }


[failure] 437-437: utils/middleware.test.ts > Middleware > withError > should return 400 for SafeError
Error: after was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context
❯ after ../../node_modules/.pnpm/next@15.5.6_@babel+core@7.28.5_@opentelemetry+api@1.9.0_react-dom@19.1.1_react@19.1.1/node_modules/next/src/server/after/after.ts:14:11
❯ flushLogger utils/middleware.ts:437:5
❯ utils/middleware.ts:93:7
❯ utils/middleware.test.ts:127:24

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: { __NEXT_ERROR_CODE: 'E468' }


[failure] 437-437: utils/middleware.test.ts > Middleware > withError > should return 400 for ZodError
Error: after was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context
❯ after ../../node_modules/.pnpm/next@15.5.6_@babel+core@7.28.5_@opentelemetry+api@1.9.0_react-dom@19.1.1_react@19.1.1/node_modules/next/src/server/after/after.ts:14:11
❯ flushLogger utils/middleware.ts:437:5
❯ utils/middleware.ts:93:7
❯ utils/middleware.test.ts:112:24

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: { __NEXT_ERROR_CODE: 'E468' }


[failure] 437-437: utils/middleware.test.ts > Middleware > withError > should call the handler and return its response on success
Error: after was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context
❯ after ../../node_modules/.pnpm/next@15.5.6_@babel+core@7.28.5_@opentelemetry+api@1.9.0_react-dom@19.1.1_react@19.1.1/node_modules/next/src/server/after/after.ts:14:11
❯ flushLogger utils/middleware.ts:437:5
❯ utils/middleware.ts:93:7
❯ utils/middleware.test.ts:97:24

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: { __NEXT_ERROR_CODE: 'E468' }

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: cubic · AI code reviewer
🔇 Additional comments (7)
apps/web/utils/logger.ts (1)

76-76: LGTM: Flush capability added consistently across all logger variants.

The flush implementations are appropriate for each logger type:

  • Console logger uses a no-op since console writes are synchronous
  • Axiom logger delegates to the underlying log.flush() for async flushing
  • Null logger uses a no-op as expected

This provides a uniform async flush interface across all logger variants, supporting the per-request logging lifecycle introduced in this PR.

Also applies to: 107-107, 120-120

apps/web/app/api/ai/models/route.ts (1)

17-18: LGTM: Successfully migrated to per-request logging.

The route handler now correctly:

  • Passes the scope identifier "api/ai/models" to withEmailAccount for contextual logging
  • Uses req.logger instead of a module-level logger for error reporting
  • Accesses authentication context via req.auth

This aligns with the per-request logging pattern established by the middleware changes.

Also applies to: 38-38

apps/web/utils/middleware.ts (5)

58-93: LGTM: Per-request logger implementation is solid.

The changes correctly implement per-request logging:

  • Creates a scoped logger with requestId and url context at the start of each request
  • Attaches the logger to the request object for downstream access
  • Flushes logs at appropriate lifecycle points (after middleware, after handler, on error)
  • Uses the per-request logger for all error logging within the middleware

The fallback to the module-level logger in getLogger is a good defensive pattern.

Also applies to: 113-113, 152-155


179-180: LGTM: Logger enrichment through middleware chain is well-designed.

Each middleware layer progressively enriches the logger context:

  • authMiddleware: Adds userId
  • emailAccountMiddleware: Adds emailAccountId, email, and optionally isOrgAdmin
  • emailProviderMiddleware: Adds provider

Error logging at authorization checkpoints includes relevant context, making debugging easier. The pattern of cloning the logger with .with() at each stage is correct.

Also applies to: 206-206, 216-216, 235-239, 244-244, 254-254, 298-300, 304-308


318-346: LGTM: Middleware overloads maintain backward compatibility.

The function overloads for all public middlewares (withError, withAuth, withEmailAccount, withEmailProvider) are consistently implemented:

  • New overload accepts a scope string for contextual logging
  • Original signature remains unchanged for backward compatibility
  • Runtime type checking correctly routes to the appropriate implementation

This allows gradual migration to scoped logging without breaking existing code.

Also applies to: 348-362, 364-392, 394-415


428-431: LGTM: Safe logger accessor with fallback.

The getLogger utility safely extracts the per-request logger and falls back to the module-level logger if unavailable. This defensive pattern ensures logging never fails even if the logger wasn't properly attached.


26-41: LGTM: Type hierarchy cleanly integrates logger.

The type definitions correctly establish a hierarchy where:

  • RequestWithLogger introduces the logger property
  • RequestWithAuth and RequestWithEmailAccount extend it, inheriting the logger

This ensures type safety and makes the logger available on all authenticated requests without duplicating the property declaration.

Comment on lines +433 to +441
function flushLogger(req: NextRequest) {
const reqWithLogger = req as RequestWithLogger;
if (reqWithLogger.logger) {
const loggerToFlush = reqWithLogger.logger;
after(async () => {
await loggerToFlush.flush();
});
}
}
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 | 🔴 Critical

Fix test failures: after() requires request context.

The after() API from Next.js 15 is only available within request contexts and throws when called in test environments. All middleware tests are currently failing because of this.

Wrap the after() call in a try-catch to gracefully handle test environments:

 function flushLogger(req: NextRequest) {
   const reqWithLogger = req as RequestWithLogger;
   if (reqWithLogger.logger) {
     const loggerToFlush = reqWithLogger.logger;
-    after(async () => {
-      await loggerToFlush.flush();
-    });
+    try {
+      after(async () => {
+        await loggerToFlush.flush();
+      });
+    } catch (error) {
+      // after() is not available outside request context (e.g., in tests)
+      // Fall back to immediate flush
+      loggerToFlush.flush().catch(() => {
+        // Ignore flush errors in fallback
+      });
+    }
   }
 }

This ensures logs are still flushed in test environments while preserving the async behavior in production.

🧰 Tools
🪛 GitHub Actions: Run Tests

[error] 437-439: Runtime error: 'after' was called outside a request scope. This is caused by Next.js dynamic API wrong context in middleware tests. Triggered during test step 'pnpm -F inbox-zero-ai test'.

🪛 GitHub Check: test

[failure] 437-437: utils/middleware.test.ts > Middleware > withEmailAccount > should return 403 if email account ID is invalid
Error: after was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context
❯ after ../../node_modules/.pnpm/next@15.5.6_@babel+core@7.28.5_@opentelemetry+api@1.9.0_react-dom@19.1.1_react@19.1.1/node_modules/next/src/server/after/after.ts:14:11
❯ flushLogger utils/middleware.ts:437:5
❯ utils/middleware.ts:93:7
❯ utils/middleware.test.ts:302:24

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: { __NEXT_ERROR_CODE: 'E468' }


[failure] 437-437: utils/middleware.test.ts > Middleware > withEmailAccount > should return 403 if email account header is missing
Error: after was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context
❯ after ../../node_modules/.pnpm/next@15.5.6_@babel+core@7.28.5_@opentelemetry+api@1.9.0_react-dom@19.1.1_react@19.1.1/node_modules/next/src/server/after/after.ts:14:11
❯ flushLogger utils/middleware.ts:437:5
❯ utils/middleware.ts:93:7
❯ utils/middleware.test.ts:271:24

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: { __NEXT_ERROR_CODE: 'E468' }


[failure] 437-437: utils/middleware.test.ts > Middleware > withEmailAccount > should call handler with email account info if header exists and account is valid
Error: after was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context
❯ after ../../node_modules/.pnpm/next@15.5.6_@babel+core@7.28.5_@opentelemetry+api@1.9.0_react-dom@19.1.1_react@19.1.1/node_modules/next/src/server/after/after.ts:14:11
❯ flushLogger utils/middleware.ts:437:5
❯ utils/middleware.ts:93:7
❯ utils/middleware.test.ts:239:7

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: { __NEXT_ERROR_CODE: 'E468' }


[failure] 437-437: utils/middleware.test.ts > Middleware > withAuth > should return 401 if session does not exist
Error: after was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context
❯ after ../../node_modules/.pnpm/next@15.5.6_@babel+core@7.28.5_@opentelemetry+api@1.9.0_react-dom@19.1.1_react@19.1.1/node_modules/next/src/server/after/after.ts:14:11
❯ flushLogger utils/middleware.ts:437:5
❯ utils/middleware.ts:93:7
❯ utils/middleware.test.ts:200:24

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: { __NEXT_ERROR_CODE: 'E468' }


[failure] 437-437: utils/middleware.test.ts > Middleware > withAuth > should call the handler with auth info if session exists
Error: after was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context
❯ after ../../node_modules/.pnpm/next@15.5.6_@babel+core@7.28.5_@opentelemetry+api@1.9.0_react-dom@19.1.1_react@19.1.1/node_modules/next/src/server/after/after.ts:14:11
❯ flushLogger utils/middleware.ts:437:5
❯ utils/middleware.ts:93:7
❯ utils/middleware.test.ts:184:7

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: { __NEXT_ERROR_CODE: 'E468' }


[failure] 437-437: utils/middleware.test.ts > Middleware > withError > should return 500 and capture unhandled errors
Error: after was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context
❯ after ../../node_modules/.pnpm/next@15.5.6_@babel+core@7.28.5_@opentelemetry+api@1.9.0_react-dom@19.1.1_react@19.1.1/node_modules/next/src/server/after/after.ts:14:11
❯ flushLogger utils/middleware.ts:437:5
❯ utils/middleware.ts:93:7
❯ utils/middleware.test.ts:160:24

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: { __NEXT_ERROR_CODE: 'E468' }


[failure] 437-437: utils/middleware.test.ts > Middleware > withError > should handle common errors using checkCommonErrors
Error: after was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context
❯ after ../../node_modules/.pnpm/next@15.5.6_@babel+core@7.28.5_@opentelemetry+api@1.9.0_react-dom@19.1.1_react@19.1.1/node_modules/next/src/server/after/after.ts:14:11
❯ flushLogger utils/middleware.ts:437:5
❯ utils/middleware.ts:93:7
❯ utils/middleware.test.ts:143:24

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: { __NEXT_ERROR_CODE: 'E468' }


[failure] 437-437: utils/middleware.test.ts > Middleware > withError > should return 400 for SafeError
Error: after was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context
❯ after ../../node_modules/.pnpm/next@15.5.6_@babel+core@7.28.5_@opentelemetry+api@1.9.0_react-dom@19.1.1_react@19.1.1/node_modules/next/src/server/after/after.ts:14:11
❯ flushLogger utils/middleware.ts:437:5
❯ utils/middleware.ts:93:7
❯ utils/middleware.test.ts:127:24

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: { __NEXT_ERROR_CODE: 'E468' }


[failure] 437-437: utils/middleware.test.ts > Middleware > withError > should return 400 for ZodError
Error: after was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context
❯ after ../../node_modules/.pnpm/next@15.5.6_@babel+core@7.28.5_@opentelemetry+api@1.9.0_react-dom@19.1.1_react@19.1.1/node_modules/next/src/server/after/after.ts:14:11
❯ flushLogger utils/middleware.ts:437:5
❯ utils/middleware.ts:93:7
❯ utils/middleware.test.ts:112:24

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: { __NEXT_ERROR_CODE: 'E468' }


[failure] 437-437: utils/middleware.test.ts > Middleware > withError > should call the handler and return its response on success
Error: after was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context
❯ after ../../node_modules/.pnpm/next@15.5.6_@babel+core@7.28.5_@opentelemetry+api@1.9.0_react-dom@19.1.1_react@19.1.1/node_modules/next/src/server/after/after.ts:14:11
❯ flushLogger utils/middleware.ts:437:5
❯ utils/middleware.ts:93:7
❯ utils/middleware.test.ts:97:24

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: { __NEXT_ERROR_CODE: 'E468' }

🤖 Prompt for AI Agents
In apps/web/utils/middleware.ts around lines 433 to 441, the call to after()
runs outside a Next.js request context in tests and throws; wrap the after()
invocation in a try-catch so that in normal runtime you call after(() => async
flush) and in the catch block (tests) call logger.flush() directly (await) to
ensure logs are flushed without using after(); keep using reqWithLogger and
loggerToFlush as currently declared.

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

1 issue found across 3 files

Prompt for AI agents (all 1 issues)

Understand the root cause of the following 1 issues and fix them.


<file name="apps/web/utils/middleware.ts">

<violation number="1" location="apps/web/utils/middleware.ts:437">
Guard after() usage to avoid throwing outside a request context. Wrap the call in try/catch and fall back to a direct logger.flush() when not in request scope to prevent runtime errors.</violation>
</file>

React with 👍 or 👎 to teach cubic. Mention @cubic-dev-ai to give feedback, ask questions, or re-run the review.

const reqWithLogger = req as RequestWithLogger;
if (reqWithLogger.logger) {
const loggerToFlush = reqWithLogger.logger;
after(async () => {
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Nov 9, 2025

Choose a reason for hiding this comment

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

Guard after() usage to avoid throwing outside a request context. Wrap the call in try/catch and fall back to a direct logger.flush() when not in request scope to prevent runtime errors.

Prompt for AI agents
Address the following comment on apps/web/utils/middleware.ts at line 437:

<comment>Guard after() usage to avoid throwing outside a request context. Wrap the call in try/catch and fall back to a direct logger.flush() when not in request scope to prevent runtime errors.</comment>

<file context>
@@ -314,3 +424,18 @@ function isErrorWithConfigAndHeaders(
+  const reqWithLogger = req as RequestWithLogger;
+  if (reqWithLogger.logger) {
+    const loggerToFlush = reqWithLogger.logger;
+    after(async () =&gt; {
+      await loggerToFlush.flush();
+    });
</file context>
Fix with Cubic

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0eef552 and 0967b95.

📒 Files selected for processing (7)
  • apps/web/__tests__/ai-detect-recurring-pattern.test.ts (0 hunks)
  • apps/web/__tests__/setup.ts (1 hunks)
  • apps/web/app/api/sso/signin/route.test.ts (0 hunks)
  • apps/web/utils/auth.test.ts (0 hunks)
  • apps/web/utils/cron.test.ts (0 hunks)
  • apps/web/utils/encryption.test.ts (0 hunks)
  • apps/web/vitest.config.mts (1 hunks)
💤 Files with no reviewable changes (5)
  • apps/web/tests/ai-detect-recurring-pattern.test.ts
  • apps/web/utils/auth.test.ts
  • apps/web/app/api/sso/signin/route.test.ts
  • apps/web/utils/cron.test.ts
  • apps/web/utils/encryption.test.ts
🧰 Additional context used
📓 Path-based instructions (8)
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Path aliases: Use @/ for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Leverage TypeScript inference for better DX

Files:

  • apps/web/__tests__/setup.ts
!{.cursor/rules/*.mdc}

📄 CodeRabbit inference engine (.cursor/rules/cursor-rules.mdc)

Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location

Files:

  • apps/web/__tests__/setup.ts
  • apps/web/vitest.config.mts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)

**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod

Files:

  • apps/web/__tests__/setup.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)

**/*.{ts,tsx}: Use createScopedLogger for logging in backend TypeScript files
Typically add the logger initialization at the top of the file when using createScopedLogger
Only use .with() on a logger instance within a specific function, not for a global logger

Import Prisma in the project using import prisma from "@/utils/prisma";

**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.

Files:

  • apps/web/__tests__/setup.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use elements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...

Files:

  • apps/web/__tests__/setup.ts
!pages/_document.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.

Files:

  • apps/web/__tests__/setup.ts
  • apps/web/vitest.config.mts
apps/web/__tests__/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/llm.mdc)

Place LLM-specific tests under apps/web/tests/

Files:

  • apps/web/__tests__/setup.ts
**/__tests__/**

📄 CodeRabbit inference engine (.cursor/rules/testing.mdc)

Place AI tests in the __tests__ directory and exclude them from the default test run (they use a real LLM)

Files:

  • apps/web/__tests__/setup.ts
🧠 Learnings (18)
📓 Common learnings
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Use Vitest in LLM tests and import { describe, expect, test, vi, beforeEach } from "vitest"
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-09-20T18:24:34.280Z
Learning: Applies to **/*.test.{ts,tsx} : Use Vitest (`vitest`) as the testing framework
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Mock the Next.js server runtime marker by adding vi.mock("server-only", () => ({})) in LLM tests
📚 Learning: 2025-10-02T23:23:48.064Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Mock the Next.js server runtime marker by adding vi.mock("server-only", () => ({})) in LLM tests

Applied to files:

  • apps/web/__tests__/setup.ts
📚 Learning: 2025-09-20T18:24:34.280Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-09-20T18:24:34.280Z
Learning: Applies to **/*.test.{ts,tsx} : In tests, mock the `server-only` module with `vi.mock("server-only", () => ({}));`

Applied to files:

  • apps/web/__tests__/setup.ts
  • apps/web/vitest.config.mts
📚 Learning: 2025-10-02T23:23:48.064Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Use Vitest in LLM tests and import { describe, expect, test, vi, beforeEach } from "vitest"

Applied to files:

  • apps/web/__tests__/setup.ts
  • apps/web/vitest.config.mts
📚 Learning: 2025-09-20T18:24:34.280Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-09-20T18:24:34.280Z
Learning: Applies to **/*.test.{ts,tsx} : Clean up mocks between tests (e.g., `vi.clearAllMocks()` in `beforeEach`)

Applied to files:

  • apps/web/__tests__/setup.ts
  • apps/web/vitest.config.mts
📚 Learning: 2025-09-20T18:24:34.280Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-09-20T18:24:34.280Z
Learning: Applies to **/*.test.{ts,tsx} : Mock external dependencies in tests

Applied to files:

  • apps/web/__tests__/setup.ts
  • apps/web/vitest.config.mts
📚 Learning: 2025-10-02T23:23:48.064Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Do not mock the actual LLM call in these tests; exercise real LLM integrations

Applied to files:

  • apps/web/__tests__/setup.ts
📚 Learning: 2025-10-02T23:23:48.064Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Call vi.clearAllMocks() in a beforeEach for LLM tests

Applied to files:

  • apps/web/__tests__/setup.ts
  • apps/web/vitest.config.mts
📚 Learning: 2025-09-20T18:24:34.280Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-09-20T18:24:34.280Z
Learning: Applies to **/*.test.{ts,tsx} : Use Vitest (`vitest`) as the testing framework

Applied to files:

  • apps/web/__tests__/setup.ts
  • apps/web/vitest.config.mts
📚 Learning: 2025-10-02T23:23:48.064Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Test both AI and non-AI paths, including cases where no AI processing is required

Applied to files:

  • apps/web/__tests__/setup.ts
  • apps/web/vitest.config.mts
📚 Learning: 2025-09-20T18:24:34.280Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-09-20T18:24:34.280Z
Learning: Applies to **/*.test.{ts,tsx} : When testing code that uses Prisma, mock it with `vi.mock("@/utils/prisma")` and use the mock from `@/utils/__mocks__/prisma`

Applied to files:

  • apps/web/__tests__/setup.ts
📚 Learning: 2025-09-20T18:24:34.280Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-09-20T18:24:34.280Z
Learning: Applies to **/*.test.{ts,tsx} : Use provided helpers for mocks: import `{ getEmail, getEmailAccount, getRule }` from `@/__tests__/helpers`

Applied to files:

  • apps/web/__tests__/setup.ts
📚 Learning: 2025-10-02T23:23:48.064Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Gate LLM tests behind RUN_AI_TESTS using describe.runIf(process.env.RUN_AI_TESTS === "true")

Applied to files:

  • apps/web/vitest.config.mts
📚 Learning: 2025-10-02T23:23:48.064Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Include standard test cases: happy path, error handling, edge cases (empty/null), different user configurations, and various input formats

Applied to files:

  • apps/web/vitest.config.mts
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/**/{.env.example,env.ts,turbo.json} : Add environment variables to `.env.example`, `env.ts`, and `turbo.json`

Applied to files:

  • apps/web/vitest.config.mts
📚 Learning: 2025-09-20T18:24:34.280Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-09-20T18:24:34.280Z
Learning: Applies to **/*.test.{ts,tsx} : Colocate tests next to the file under test (e.g., dir/format.ts with dir/format.test.ts)

Applied to files:

  • apps/web/vitest.config.mts
📚 Learning: 2025-09-20T18:24:34.280Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-09-20T18:24:34.280Z
Learning: Applies to **/*.test.{ts,tsx} : Each test should be independent

Applied to files:

  • apps/web/vitest.config.mts
📚 Learning: 2025-07-20T09:03:06.318Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-07-20T09:03:06.318Z
Learning: Applies to **/*.{test,spec}.{js,jsx,ts,tsx} : Don't use export or module.exports in test files.

Applied to files:

  • apps/web/vitest.config.mts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: test
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
apps/web/vitest.config.mts (1)

9-9: LGTM! Standard Vitest setup configuration.

The setupFiles configuration correctly points to the test setup module, enabling centralized test initialization before tests run.

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

Reviewed changes from recent commits (found 1 issue).

1 issue found across 7 files

Prompt for AI agents (all 1 issues)

Understand the root cause of the following 1 issues and fix them.


<file name="apps/web/__tests__/setup.ts">

<violation number="1" location="apps/web/__tests__/setup.ts:10">
We need this mock to await async callbacks the same way the inline e2e mocks do; otherwise work scheduled with after() can still be running when the test asserts, causing race conditions. Please make the wrapper async and await fn().</violation>
</file>

React with 👍 or 👎 to teach cubic. Mention @cubic-dev-ai to give feedback, ask questions, or re-run the review.

...actual,
after: (fn: () => void | Promise<void>) => {
// In tests, just run the function synchronously
return fn();
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Nov 9, 2025

Choose a reason for hiding this comment

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

We need this mock to await async callbacks the same way the inline e2e mocks do; otherwise work scheduled with after() can still be running when the test asserts, causing race conditions. Please make the wrapper async and await fn().

Prompt for AI agents
Address the following comment on apps/web/__tests__/setup.ts at line 10:

<comment>We need this mock to await async callbacks the same way the inline e2e mocks do; otherwise work scheduled with after() can still be running when the test asserts, causing race conditions. Please make the wrapper async and await fn().</comment>

<file context>
@@ -0,0 +1,13 @@
+    ...actual,
+    after: (fn: () =&gt; void | Promise&lt;void&gt;) =&gt; {
+      // In tests, just run the function synchronously
+      return fn();
+    },
+  };
</file context>

✅ Addressed in 0e66fda

@elie222 elie222 merged commit f38f04e into main Nov 9, 2025
9 of 11 checks passed
@elie222 elie222 deleted the feat/logger-api branch November 9, 2025 21:54
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

No issues found across 6 files

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant