Skip to content

An exclusion middleware made to handle exceptions from running the provided function based on the current req.path.

License

Notifications You must be signed in to change notification settings

tom-saetran/cors-except

Repository files navigation

NPM license GitHub contributors GitHub issues GitHub release (latest by date) GitHub release date NPM downloads GitHub package.json dynamic

cors-except

This package provides a middleware that allows CORS requests to be selectively checked. It is useful for services that needs to be accessed by browsers.

Usage

import cors from "cors"
import express from "express"
import except from "cors-except"

const server = express()

const whitelist = ["https://frontend.url"]
const corsOptions = {
  origin: (origin, next) => {
    try {
      if (whitelist.indexOf(origin) !== -1) next(null, true)
      else next(new Error("Not allowed by CORS"))
    } catch (error) {
      next(error)
    }
  }
}

const corsExceptions = ["/without-cors"]
server.use(except(corsExceptions, cors(corsOptions)))

server.get("/without-cors", (_, res) => res.send("Any origin"))
server.get("*", (_, res) => res.send("corsOptions origin only"))
server.listen(() => console.log("Server started"))

About

An exclusion middleware made to handle exceptions from running the provided function based on the current req.path.

Resources

License

Security policy

Stars

Watchers

Forks

Packages

No packages published