Mastering CORS and Cross‑Domain Solutions for Java Interviews

This guide explains the browser same‑origin policy, why cross‑origin restrictions exist, and presents five practical solutions—including CORS, proxy servers, JSONP, postMessage, and WebSocket—along with detailed configuration examples, code snippets, performance tips, and common interview follow‑up questions.

Java Architect Handbook
Java Architect Handbook
Java Architect Handbook
Mastering CORS and Cross‑Domain Solutions for Java Interviews

Background

Browsers enforce the Same‑Origin Policy (protocol + domain + port) to prevent a page from reading resources from a different origin. AJAX requests to another origin are blocked unless the server explicitly permits them.

Common Cross‑Origin Solutions

CORS – server sets Access-Control-* response headers. Standard, works for all HTTP methods, but requires server cooperation.

Proxy server – a same‑origin front‑end server forwards API calls to the real backend, so the browser never sees a cross‑origin request.

JSONP – uses a <script> tag with a callback parameter; only GET requests and not secure, kept for legacy systems.

postMessage – window‑to‑window communication, useful for iframe embedding.

WebSocket – not subject to same‑origin restrictions, provides full‑duplex communication.

CORS Details

Simple request vs. preflight

A simple request meets three conditions (method is GET/HEAD/POST, allowed headers, content‑type is one of a few safe types). The browser sends it directly and checks the Access-Control-Allow-Origin header in the response.

For non‑simple requests the browser first sends an OPTIONS preflight request. The server must respond with Access-Control-Allow-Methods, Access-Control-Allow-Headers and optionally Access-Control-Max-Age to cache the result.

Typical CORS response headers

Access-Control-Allow-Origin

– allowed origin, e.g. * or

http://localhost:3000
Access-Control-Allow-Methods

– e.g.

GET, POST, PUT, DELETE
Access-Control-Allow-Headers

– e.g.

Content-Type, X-Token
Access-Control-Allow-Credentials

true if cookies are allowed (cannot be * when true) Access-Control-Max-Age – preflight cache time in seconds Access-Control-Expose-Headers – headers that the browser may expose to JavaScript

Spring Boot configuration example

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOriginPatterns("*")   // SpringBoot 2.4+; use specific domains in production
                .allowedMethods("GET","POST","PUT","DELETE","OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
}

A filter‑based version can set the same headers manually and return 200 for OPTIONS requests.

Proxy Server Solution

The same‑origin restriction applies only to browsers. By routing API calls through a same‑origin development server, the browser sees no cross‑origin request.

Vite proxy configuration

// vite.config.js
export default {
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        rewrite: path => path.replace(/^\/api/, '')
      }
    }
  }
}

Nginx reverse‑proxy (production)

# /etc/nginx/conf.d/example.conf
server {
    listen 80;
    server_name example.com;

    location / {
        root /var/www/html;
        index index.html;
    }

    location /api/ {
        proxy_pass http://backend-server:8080/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

JSONP

Works because <script> tags are exempt from the same‑origin policy. The client supplies a callback name; the server returns JavaScript that calls that function.

function jsonp(url, callback) {
  const cb = 'jsonp_' + Date.now();
  window[cb] = function(data) {
    callback(data);
    delete window[cb];
    document.body.removeChild(script);
  };
  const script = document.createElement('script');
  script.src = `${url}?callback=${cb}`;
  document.body.appendChild(script);
}

// usage
jsonp('http://api.example.com/user', data => console.log(data));

Limitations: GET only, security risk if the response is compromised, and no direct access to HTTP status codes.

Cross‑Origin with Cookies

When credentials are required, the client must send credentials: 'include' (fetch) or withCredentials: true (axios). The server must set a concrete Access-Control-Allow-Origin value and Access-Control-Allow-Credentials: true. Cookies themselves must have SameSite=None; Secure and be served over HTTPS.

Key Points for Interviews

Understand the purpose of the Same‑Origin Policy.

Be able to explain the CORS workflow, simple vs. preflight, and required response headers.

Know when to use a proxy, JSONP, postMessage or WebSocket.

Remember that Access-Control-Allow-Credentials: true forbids using * for Access-Control-Allow-Origin.

proxyWeb developmentCORSCross-OriginBrowser SecurityJSONPJava Interview
Java Architect Handbook
Written by

Java Architect Handbook

Focused on Java interview questions and practical article sharing, covering algorithms, databases, Spring Boot, microservices, high concurrency, JVM, Docker containers, and ELK-related knowledge. Looking forward to progressing together with you.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.