CORS & Security Basics in Express.js
When building backend APIs, security is one of the most important aspects to consider. One of the common issues developers face is Cross-Origin Resource Sharing (CORS), which controls how resources are shared between different domains.
Along with CORS, understanding basic security practices helps protect your application from unauthorized access and common web vulnerabilities.
What is CORS?
CORS (Cross-Origin Resource Sharing) is a security feature implemented by browsers that restricts web pages from making requests to a different domain than the one that served the page.
For example:
- Frontend running on
http://localhost:3000 - Backend running on
http://localhost:5000
In this case, the browser blocks requests unless the server explicitly allows them using CORS.
Why CORS is Important
- Prevents unauthorized access to APIs
- Protects user data
- Ensures secure cross-domain communication
Using CORS in Express.js
The easiest way to enable CORS in an Express application is by using the cors middleware.
Installation
Basic Example
This allows all origins to access your API.
Restricting CORS
For better security, you should allow only specific origins:
This ensures that only requests from the specified domain are allowed.
Handling Specific Methods
Security Best Practices
1. Use Helmet for Security Headers
Helmet helps secure your Express app by setting various HTTP headers.
2. Validate User Input
Always validate incoming data to prevent malicious input.
3. Use HTTPS
Always serve your application over HTTPS to encrypt data transmission.
4. Rate Limiting
Prevent abuse by limiting the number of requests:
5. Avoid Exposing Sensitive Data
Never expose internal errors, stack traces, or sensitive information in API responses.
Common Security Risks
- Cross-Site Scripting (XSS)
- SQL Injection
- Cross-Site Request Forgery (CSRF)
- Unvalidated user input
Real-World Use Cases
- Frontend-backend communication
- Public APIs with restricted access
- Microservices communication
Common Mistakes
- Allowing all origins in production
- Not restricting HTTP methods
- Ignoring security headers
- Not using HTTPS
Conclusion
CORS is essential for controlling access to your APIs, while security best practices ensure your application remains safe from common vulnerabilities.
By properly configuring CORS and following security guidelines, you can build secure and scalable backend applications using Express.js.

