Yilmaz
Yilmaz

Reputation: 49709

how to set up cors() in typescript express

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 set up 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>'

Upvotes: 13

Views: 31796

Answers (6)

Mahesh Jamdade
Mahesh Jamdade

Reputation: 20369

You can allow requests from specific origins like this

  1. Install Cors
npm install @types/cors
  1. Configure
const corsOptions = {
    origin: [process.env.CLIENT_BASE_URL || 'http://localhost:3000', 'https://www.getpostman.com'], // Allow requests only from these origins
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
    credentials: true, // Allow cookies, if your application uses them
    optionsSuccessStatus: 204, 
    // headers: 'Content-Type, Authorization, Content-Length, X-Requested-With',
};
  1. Usage
app.use(cors(corsOptions)); // use before the routes

app.use(express.json());
app.use(bodyParser.json());

app.use('/api/v1', publicRoutes);

Upvotes: 1

jazoe
jazoe

Reputation: 9

All you need to do is install the @types package for cors:

npm i -D @types/cors

Cors doesn't automatically come with its type definitions when you import cors. Thus, you need to install those type definitions using the above npm installation command. Only then, will you have the types for cors and typescript will stop complaining to you. ("-D" saves them as a dev-dependency because types/typescript is only needed in the development environment before transpilation to JS)

Upvotes: -1

An update in the same thread,

app.use((cors as (options: cors.CorsOptions) => express.RequestHandler)({}));

https://github.com/DefinitelyTyped/DefinitelyTyped/issues/43909#issuecomment-1168194740

Upvotes: 0

Lucas Ferronato
Lucas Ferronato

Reputation: 92

i found this solution:

Using:

...
  "express": "^4.17.1",
  "@types/express": "^4.17.9",
...

replace ".use(cors())" for

app.use((req: Request, res: Response, next: NextFunction) => {
  next();
}, cors({ maxAge: 84600 }));

Source: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/43909#issuecomment-743156647

Upvotes: 5

KrystianKasp98
KrystianKasp98

Reputation: 41

In my case:

{
  "cors": "^2.8.5",
  "express": "^4.18.1",
  "typescript": "^4.8.4",
}

it works:

import cors = require("cors");
app.use(cors<Request>());

Upvotes: 1

DanielG
DanielG

Reputation: 2377

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>());

Upvotes: 16

Related Questions