Running ReactJS application with HTTPS and backend APIs behind a Kubernetes Ingress
I finally managed to fix this issue and the good news is that you don't need to create a self signed certificate.
The steps are the following:
- set a HOST environment variable before starting your development react server.
- adjust /etc/hosts so that 127.0.0.1 points to the value set in the HOST environment variable
- adjust your k8s ingress CORS settings to allow "cors-allow-origin" from the domain set in the HOST environment variable
- setting cookies should now work as expected.
Below are the relevant code snippets:
- npm start script
"scripts": { "start": "PORT=4000 HOST=app.urlshortner.local react-scripts start", }
notice the HOST environment variable, the PORT environment variable is optional, I'm using it because the default port 3000 is already taken.
- /etc/hosts
127.0.0.1 app.urlshortner.local 192.168.99.106 urlshortner.local
note that 192.168.99.106 is my local minikube ip address.
- Kubernetes ingress configuration
apiVersion: networking.k8s.io/v1beta1 kind: Ingress metadata: name: url-shortner-backend-services namespace: default annotations: nginx.ingress.kubernetes.io/rewrite-target: /$2 nginx.ingress.kubernetes.io/enable-cors: "true" nginx.ingress.kubernetes.io/cors-allow-origin: "http://app.urlshortner.local:4000" nginx.ingress.kubernetes.io/cors-allow-credentials: "true" spec: rules: - host: urlshortner.local http: paths: - path: /shortner(/|$)(.*) backend: serviceName: url-shortener-service servicePort: 3000 - path: /auth(/|$)(.*) backend: serviceName: auth-service servicePort: 3000
What matters here is the following:
nginx.ingress.kubernetes.io/enable-cors: "true" nginx.ingress.kubernetes.io/cors-allow-origin: "http://app.urlshortner.local:4000" nginx.ingress.kubernetes.io/cors-allow-credentials: "true"
- axios instance used
import axios from "axios"; let baseURL = ''; if (process.env.NODE_ENV === 'development') { baseURL = 'http://urlshortner.local'; } export default axios.create({ baseURL, withCredentials: true });
- How the cookie is set:
c.SetCookie("token", resp.Token, 3600, "/", ".urlshortner.local", false, true)
note the domain used. It starts with a "."
I hope this helps someone.