What is CORS: Cross-Origin Resource Sharing in Web Development

ASHISH GUPTA

ASHISH GUPTA

5 min read

  • react
  • python
  • java
  • node js
CorsCoverImage

Are you facing CORS error while developing a web application. then don't worry about this because in this blog post i will cover every thing about CORS by which after reading this post you can easily solve this problem.

introduction

In mern stack or other development tools when you connecting your Front-end with your Back-end, getting a famous error in console it's none of them its CORS. CORS stands for Cross-Origin Resource sharing.CORS is a security feature that allows or restricts resources on a web page to be requested from another domain outside the domain from which the resource originated.

What is CORS?

CORS, or Cross-Origin Resource Sharing, is a web protocol by which browser ensures that the web application access resource as per their authority. by default browser ensure that same-origin policy by which web page can only access the self domain data. CORS provides methods in which you can access resource of different domain from the header. you'll need to allow the frontend domain to your backend server.

corserrordetail

Why is CORS Important?

CORS is very useful in modern full-stack web development because:-

  • Increase Security : - It prevents malicious website to accessing the user sensitive data from another domain.

  • Allow API Interaction : - It allows web applications to interact with APIs hosted on different domains, which is crucial for microservices architecture and third-party integrations.

These are the reasons by which we CORS important.

How CORS Works

its work on the header by those header it control the communication between the fronted and backend.

key headers are:

  • Access-Control-Allow-Origin: by this header you can specify that which origin can excess the resource.

  • Access-Control-Allow-Methods: Lists the HTTP methods that are allowed when accessing the resource.

  • Access-Control-Allow-Headers: Specifies which headers can be used in the actual request.

  • Access-Control-Allow-Credentials: Indicates whether credentials (such as cookies) can be sent with the request.

  • Access-Control-Expose-Headers: Indicates which headers are safe to expose to the API of a CORS API specification.

  • Access-Control-Max-Age: Specifies how long the results of a preflight request can be cached.

exampleofCOrs

Example of a CORS Request Flow:

  1. Simple Request: When a browser makes a simple request (like a GET request), it includes the Origin header. If the server’s response includes the Access-Control-Allow-Origin header with a value that matches the requesting origin, the request is allowed.

  2. Preflight Request: For more API requests (like those with custom headers or HTTP methods like PUT or DELETE), browser sends the dame preflight request after if server respond for that request then browser sends actual request to the server.

Common CORS synopsis

  • Fetching Data from an API:- A website hosted on https://biyondbytes.com made request to fetch data from an API at https://api.biyondbytes.com. The API server must include the Access-Control-Allow-Origin: https://biyondbytes.com header in its response to allow the request.

  • Loading Web Fonts:-Web fonts hosted on a CDN need to be used on a website. The CDN must include the Access-Control-Allow-Origin: * header to allow any origin to access the fonts.

Configuring CORS in Different Environments

For javascript/Typescript:-

this method is called whiteList method here you are enabling to send request and response or connection between frontend and backend.

const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors({
  origin: 'https://biyondbytes.com', //important you can type your website link like domain or http://localhost:{port number(3000)} 
  methods: 'GET,POST,PUT,DELETE',//optional
  allowedHeaders: 'Content-Type,Authorization' //optional
}));

app.get('/data', (req, res) => { //routing not necessary
  res.json({ message: 'This is CORS-enabled for https://biyondbytes.com' });
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

other method :- proxy method , here you set domain of backend in frontend as proxy.

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost:5000" //or "api.biyondbytes.com", whatever your in your backend file
}

To set up a proxy in react app using "vite". configure or modified vite.config.js to include the proxy in frontend.

// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:5000', 
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
    },
  },
});

Java/SpringBoot

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("https://example.com")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("Content-Type", "Authorization");
    }
}

Python/Flask

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "https://example.com"}})

@app.route('/api/data')
def get_data():
    return {'message': 'This is CORS-enabled for https://example.com'}

if __name__ == '__main__':
    app.run(port=5000)

Troubleshoot the CORS problems

Common CORS Problems

  • The server did not include the Access-Control-Allow-Origin header in the response of backend file.

  • The API request failed due to missing or incorrect CORS headers.

  • he requested method is not included in the Access-Control-Allow-Methods header.

Troubleshooting Steps

  1. Check Server Configuration:

  2. Review HTTP Methods and Headers:

Conclusion and Best Practices

CORS is a best feature for enable secure cross-origin requests in website. To professionally use of CORS, follow these best practices which done by experienced software engineers in MNCs company:

  • Whitelist Specific Origins: Avoid using wildcards (*) and instead specify trusted domains or known domain.

  • Limit Allowed Methods and Headers: Only give permission the necessary HTTP methods and headers.

  • Enable Credentials Carefully: Only allow credentials when absolutely necessary and ensure secure handling.

By understanding and correctly configuring CORS, you can enhance the security and functionality of your web applications.

these are methods in various programming language to resolve CORS problem. enjoy your development journey give like this blog and comment other best practice we will consider it and improve it.

Thank you

Happy coding!

ASHISH GUPTA

ASHISH GUPTA

Creative, Elegant and Visionary

Latest

from the blog

The latest industry news,interviews and resources

Python's One-Line if else Magic

Python's One-Line if else Magic

Python's One-Line if else Magic

Best Alternatives to Adobe's Generative Fill AI Free

Best Alternatives to Adobe's Generative Fill AI Free

Fill for free online which enhance and boost your design works

Join our newsletter

we'll send you a nice letter once per week. No spam.

BiyondBytes

© 2024 BiyondBytes. All rights reserved.