Skip to content

Type Error: NextApiRequest not assignable to Request | NextRequest | undefined #71

@ericsen-tsai

Description

@ericsen-tsai

Description:
Encountering a type error when using NextApiRequest and NextApiResponse in a Next.js API route handler. The error message indicates that NextApiRequest is not assignable to the type Request | NextRequest | undefined.

Error Details:

Type 'NextApiRequest' is not assignable to type 'Request | NextRequest | undefined'.
  Type 'NextApiRequest' is missing the following properties from type 'NextRequest': geo, ip, nextUrl, page, and 19 more.ts(2322)

Code Snippet:

import { setCookie } from 'cookies-next';
import { NextApiRequest, NextApiResponse } from 'next';

...

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<ClientServiceAuthResponse | ClientServiceAuthError>
) {
  try {
    const serverToken = await getServerToken();
    const clientToken = {
      ...
    };

    setCookie(TOKEN_COOKIE, clientToken.accessToken, {
      req,
      res,
      expires: new Date(Date.now() + clientToken.expiresIn),
    });
    res.status(200).json(clientToken);
  } catch (e) {
    res.status(500).json({ message: 'Internal Server Error' });
  }
}

Steps to Reproduce:

  1. Implement the given API route handler in a Next.js project.
  2. Run tsc --project tsconfig.json.
  3. Observe the type error in the terminal output.

Expected Behavior:
The TypeScript types should match, and the project should compile without type errors.

Actual Behavior:
TypeScript throws a type error, indicating that NextApiRequest is not assignable to the expected type.

Additional Context:

  • Next.js version: 14.1.4
  • TypeScript version: 5.4.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions