Intermediate level · Module 5: Connecting Front End and API · Lesson 3 of 3
CORS and Environments
Understand cross-origin requests and configure the front end and API for development and production.
In this lesson you will
- Explain CORS and configure it safely on the API
- Configure separate development and production settings
Key concepts
originCORS headersdevelopment proxyenvironment variables in front-end builds
The lesson
Browsers block a page from reading responses from a different origin (scheme, domain or port) unless the server allows it with CORS headers. A React dev server on port 5173 calling an API on port 3000 is cross-origin.
Configure CORS on the API to allow only the origins you trust, such as your production site, rather than every origin. In development, a dev-server proxy can forward /api calls and avoid CORS entirely.
Front-end build tools expose selected environment variables, such as the API URL, at build time. Remember that everything in front-end code is public: never put secrets there.
Step by step
- Reproduce a CORS error and read the console message.
- Fix it with the dev-server proxy.
- Configure CORS on the API for the production origin only.
- Set the API URL with a build-time environment variable.
Practice activity
Configure the catalogue so it runs locally without CORS errors and is ready to point at a production API.
Expected result: Local development works and the production configuration allows only the real front-end origin.
Check your understanding
-
When is a request cross-origin?
Show answer
When the scheme, domain or port differs from the page's.
-
Can a secret be kept in a front-end environment variable?
Show answer
No; front-end code and its variables are visible to anyone.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.