Skip to content

Instantly share code, notes, and snippets.

Last active Oct 11, 2021
What would you like to do?

CORS (Cross-Origin Resource Sharing)

  • CORS is a mechanism which uses additional http headers to tell the browser whether a specefic web app can share resource with another web app (only if they have different origin)

  • In same origin can share resources very easily

  • Back then, when CORS was not standardize browser never allow applications to share resources between different origins.

Some examples:

                     --------> (not allowed)

                     --------> (not allowed)
                     --------> (not allowed)
                     --------> (not allowed)

Alt Text

  • CORS now is web standard and we can share resources

How CORS works:

Screen Shot 2021-10-11 at 14 09 52


  • Client initiates by sending “credentials: include” in Request header

  • Server sends credential with following response headers Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: *

  • Credentials can be: cookie, Authorization header or TLS Client Certificate

In the next.config.js file, a "headers" function can be created to enable CORS

module.exports = {
  async headers() {
    return [
        // matching all API routes
        source: "/api/:path*",
        headers: [
          { key: "Access-Control-Allow-Credentials", value: "true" },
          { key: "Access-Control-Allow-Origin", value: "*" },
          { key: "Access-Control-Allow-Methods", value: "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
          { key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment