Use Nginx as reverse proxy to avoid CORS error(Set-Cookie not working error)

miAlism

miAlism / November 07, 2021

2 min read

Under the development environment, CORS(Cross-Origin Resource Sharing) is an important issue to handle when develop a front-back-seperation project. Assuming that your frontend domain is localhost:3000 and your backend(API) domain is localhost:8000, and something like different ports qualifies as cross domain even though you have same origin(localhost) in both the frontend and backend. If cookies like CSRF token is generated by backend and you want to get and set it through frontend(like React), you can't set cookies in browser with accessing localhost:3000 but accessing localhost:8000 works.

You can use Nginx as reverse proxy to bypass the problem. On macOS you can install Nginx with Homebrew brew install nginx and the configure the file located in /usr/local/etc/nginx/nginx.conf. Choose a third port(like 8080) as a general endpoint to access all your site's resource includes frontend and backend(API) request. If you visit localhost:3000 to access you site before, now you should replace it with localhost:8080. The Example configuration:

/usr/local/etc/nginx/nginx.conf
server {
listen 8080;
server_name localhost;
location / {
proxy_pass http://localhost:3000;
}
# If all backend url is start with `:8000/api/`
location /api/ {
proxy_pass http://localhost:8000;
proxy_set_header Host $host;
}
}

Reference

Youtube