how to set up cors() in typescript express

Viewed 7886

In one of my projects, simply this worked:

import cors from "cors";

server.use(cors());

but currently I am having this lovely typescript warning message in my new project:

  No overload matches this call.
  The last overload gave the following error.
    Argument of type '(req: Request<never, never, never, never>, res: { statusCode?: number | undefined; setHeader(key: string, value: string): any; end(): any; }, next: (err?: any) => any) => void' is not assignable to parameter of type 'RequestHandlerParams<ParamsDictionary, any, any, ParsedQs>'.
      Type '(req: Request<never, never, never, never>, res: { statusCode?: number | undefined; setHeader(key: string, value: string): any; end(): any; }, next: (err?: any) => any) => void' is not assignable to type 'RequestHandler<ParamsDictionary, any, any, ParsedQs>'.
        Types of parameters 'req' and 'req' are incompatible.
          Type 'Request<ParamsDictionary, any, any, ParsedQs>' is not assignable to type 'Request<never, never, never, never>'.
            Type 'ParamsDictionary' is not assignable to type 'never'.ts(2769)

then I tried to setup custom cors middleware and use it:

import { NextFunction ,Request,Response} from 'express';

export const Cors=(req:Request, res:Response, next:NextFunction) => {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader(
      "Access-Control-Allow-Methods",
      "OPTIONS, GET, POST, PUT, PATCH, DELETE"
    );
    res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
    if (req.method === "OPTIONS") {
      return res.sendStatus(200);
    }
    next();
  };

   server.use(Cors());

this time i am having another lovely error :

No overload matches this call. The last overload gave the following error. Argument of type 'Response | undefined' is not assignable to parameter of type 'RequestHandlerParams<ParamsDictionary, any, any, ParsedQs>'. Type 'undefined' is not assignable to type 'RequestHandlerParams<ParamsDictionary, any, any, ParsedQs>'

2 Answers

This is because of some ambiguity in the generic typing for the cors library. The easiest way I've found to fix this is simply explicitly specify the request type for the cors method.

import { Request } from "express";
import cors from "cors";

server.use(cors<Request>());
Related