I have NodeJS api and NextJS application in Separate docker containers when I’m in host machine its working fine, but when I’m running inside docker containers its giving CORS error.
My express config in API
app.use(cors({
credentials: true,
origin: 'http://localhost:3000/' // Allowing front-end running port 3000
}));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(urlencoded({ extended: true }));
app.use(json());
app.enable("trust proxy");
app.use(methodOverride());
In front-end APP NextJS axios config
const axiosInstance = axios.create({ baseURL: 'http://localhost:4000/', withCredentials: true });
Its woking fine when im running API from host machine, with same configuration its giving CORS error in Docker.
4
Answers
Add each
localhost
+port
to thecors
options (I left some other options just for example, not relevant to your question though):This is common issue many solutions.
The correct solution depends on your requirements.The simpler solution is to run the docker container with NGINX acting as reverse proxy.
Example of nginx docker
Build it as cors
Finally make sure that nginx.conf allowing origins from request
Example of nginx.config
Add this line to your
package.json
file. then rebuild your container and start the app.As i can see your API configuration seems correct, but in your NextJS create pages/api/whatever.js and call your API from handler
this will work and its safer way to mask your back end API calls from front end.