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.
As i can see your API configuration seems correct, but in your NextJS create pages/api/whatever.js and call your API from handler
import axios from 'axios';
axios.defaults.withCredentials = true;
export default async function handler(req, res){
try {
const response = axios.post('http://localhost:4000/<your_login_api_URL>', req.body)
}catch(error) {
// handle error here
}
}
this will work and its safer way to mask your back end API calls from front end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With