Angular Security
Angular Security
Sai Reddy
saireddy-dotnetfs
return this.authService.isLoggedIn();
}
Add this guard in routing module for secure routes.
9. What are CanActivate and CanDeactivate guards?
CanActivate controls if a user can enter a route, CanDeactivate confirms if they can leave. Useful for
auth and unsaved changes. Example:
canDeactivate(): boolean {
return confirm('Leave without saving?');
}
Apply these in the route definition.
10. How do you manage user authentication in Angular?
Use login APIs, store JWT, and manage session with services. Example:
login(credentials) {
return this.http.post('/api/login', credentials);
}
Then store the token securely and use guards/interceptors.
11. What is the role of JWT in Angular security?
JWT is a compact, URL-safe token for authentication and authorization. Angular stores the token
after login and sends it with each request. Example:
localStorage.setItem('token', jwtToken);
Use interceptors to append it in request headers.
12. How can you store JWT securely in Angular?
Avoid localStorage; prefer HttpOnly cookies for security. But if you must, use sessionStorage with
caution. Example:
sessionStorage.setItem('token', jwt);
Clear it on logout and restrict sensitive logic to backend.
13. Why shouldn’t we store tokens in localStorage?
localStorage is vulnerable to XSS attacks since JavaScript can access it. A malicious script can steal
your token. It's better to use HttpOnly cookies, which JS can't access. If localStorage is used, ensure
strong XSS protection.
14. What is CSRF, and how can Angular applications prevent it?
CSRF tricks a user into sending unwanted requests while logged in. Angular prevents this using token-
based auth and disabling cookie-based auth. Servers can also validate CSRF tokens in headers. Avoid
using withCredentials unless required.
15. How do you handle HTTP Interceptors in Angular?
Use interceptors to add tokens, handle errors, or modify requests. Example:
intercept(req, next) {
const newReq = req.clone({ headers: req.headers.set('Auth', token) });
return next.handle(newReq);
}
Register it in the providers array.
16. What is the use of HttpOnly cookies with Angular?
HttpOnly cookies store tokens that JavaScript can’t access, blocking XSS. They're set from the server
side. Angular doesn’t access them but sends them automatically with requests if withCredentials is
true.
this.http.get('/api/data', { withCredentials: true });
17. How do you restrict access to a page in Angular?
Use route guards like CanActivate to allow access only if logged in. Example:
Sai Reddy
saireddy-dotnetfs
canActivate() {
return this.authService.isLoggedIn();
}
Attach guard to secured route paths.
18. What is the difference between client-side and server-side validation?
Client-side validation improves UX; server-side ensures data integrity. Angular uses form validation
for real-time feedback. But backend must also validate to stop tampering. Example:
<formControlName="email" required>
But also validate on API side.
19. How do you validate user input in Angular forms?
Use built-in or custom validators in reactive or template-driven forms. Example:
email = new FormControl('', [Validators.required, Validators.email]);
Display errors using *ngIf="email.invalid".
20. How does Angular help in protecting against clickjacking?
Angular doesn’t directly protect against clickjacking, but servers should send X-Frame-Options: DENY.
You can also avoid iframe embedding with CSP headers. On Angular side, avoid UI that can be
overlaid.
21. What is the purpose of Angular Content Security Policy (CSP)?
CSP prevents XSS by restricting sources of scripts/styles. Angular works well with CSP if inline scripts
are avoided. Example CSP:
Content-Security-Policy: script-src 'self';
Use hashed scripts when needed.
22. How do you implement password masking in Angular forms?
Use type="password" in input field. Example:
<input type="password" formControlName="password">
You can toggle visibility with a button using [type]="show ? 'text' : 'password'".
23. What are the best practices for form security in Angular?
Validate on both client and server, sanitize inputs, avoid prefilled sensitive data, and mask passwords.
Example:
form = this.fb.group({ email: ['', Validators.required] });
Also, disable autocomplete for sensitive fields.
24. How can you disable right-click or inspect in Angular apps?
Use DOM event listeners, but it’s not secure. Example:
<body (contextmenu)="false">
But users can still inspect with dev tools—this is just an obstacle, not protection.
25. What is the importance of using strict mode in TypeScript for security?
strict mode enables stricter type-checking to catch bugs early. It avoids null/undefined errors that
can lead to logic flaws. In tsconfig.json:
"strict": true
This improves code safety and reliability.
Angular TypeScript Security Interview Questions and Answers for 3–6 years of experience
Sai Reddy
saireddy-dotnetfs
You can also hide UI elements based on roles using *ngIf="isAdmin".
2. Explain the use of route guards with roles and permissions.
Create a guard that checks the user's role before allowing access. Example:
canActivate(): boolean {
return this.auth.hasRole('editor');
}
Attach this guard to routes requiring specific permissions.
3. How can you create and secure a multi-role application in Angular?
Assign roles at login and use guards and directives for restrictions. Example:
<div *ngIf="user.role === 'manager'">Manager Panel</div>
Use services to manage role-based logic and route guards for protection.
4. How do Angular interceptors enhance security?
Interceptors help enforce auth policies, modify headers, or handle errors. Example:
intercept(req, next) {
const token = this.auth.getToken();
const cloned = req.clone({ setHeaders: { Authorization: `Bearer ${token}` } });
return next.handle(cloned);
}
5. What are the best practices for handling sensitive user data on the frontend?
Never store passwords or sensitive data in the browser. Minimize what is stored (e.g., no PII).
Example:
sessionStorage.setItem('userId', response.id);
Encrypt sensitive data before storing and use HTTPS always.
6. How do you protect Angular apps from insecure direct object references (IDOR)?
Avoid exposing raw IDs on the frontend; use UUIDs or access checks. Backend should validate access.
On Angular side, avoid logic like:
this.http.get(`/api/user/${userId}`);
Backend must ensure that the user has rights to access that ID.
7. How do you implement OAuth2 with Angular?
Use Authorization Code Flow with PKCE. Redirect to the auth server, receive a code, and exchange it
for a token. Example using angular-oauth2-oidc:
this.oauthService.loadDiscoveryDocumentAndTryLogin();
Tokens are stored securely and sent in HTTP headers.
8. What are the differences between storing tokens in cookies vs localStorage?
Cookies can be HttpOnly, reducing XSS risk. localStorage is readable by JS and prone to XSS. Example:
• Use cookie for auto-sending: { withCredentials: true }.
• Use localStorage only when secure from XSS.
9. How do you refresh JWT tokens securely in Angular?
Use refresh tokens stored in HttpOnly cookies. Auto-refresh using an interceptor. Example:
intercept() { if (isExpired(token)) return refreshToken(); }
Tokens should be short-lived and rotated often.
10. What is the best way to implement logout functionality in Angular securely?
Clear tokens and call logout API. Example:
logout() {
sessionStorage.removeItem('token');
this.http.post('/api/logout', {}).subscribe();
}
Redirect to login and revoke tokens on the server.
Sai Reddy
saireddy-dotnetfs
11. How would you implement 2FA/MFA in an Angular app?
Add a second step after login using OTP or authenticator app. Example:
verifyOtp(code: string) { return this.http.post('/api/2fa', { code }); }
After success, allow access to the app.
12. How can you implement input sanitization for HTML forms?
Sanitize user inputs manually or with libraries like DOMPurify. Example:
const clean = DOMPurify.sanitize(this.userInput);
Always validate inputs both client and server side.
13. What are trusted types in Angular and how do they improve security?
Trusted types prevent XSS by enforcing safe input into DOM sinks. Angular supports them via
DomSanitizer. Example:
const safeHtml = sanitizer.bypassSecurityTrustHtml(htmlContent);
This ensures only trusted content is rendered.
14. How would you handle a token expiry scenario in Angular?
Detect expired tokens and use refresh token to get a new one. Example:
if (isExpired(token)) this.authService.refreshToken().subscribe();
Fail-safe fallback: redirect to login.
15. How to handle error logging securely in Angular?
Do not log sensitive data. Use logging services that redact personal info. Example:
logError(error) {
console.error('Error: ', { message: error.message });
}
Send sanitized logs to secure backend.
16. How do you protect against open redirects in Angular routing?
Validate any redirect URL and avoid accepting external input blindly. Example:
if (!url.startsWith('/')) return '/home';
Never trust URLs from query params or localStorage without checks.
17. What is Subresource Integrity (SRI), and how can Angular apps use it?
SRI ensures loaded resources (scripts/styles) aren’t tampered with. Add integrity/hash to <script>
tag. Example:
<script src="lib.js" integrity="sha384-abc..." crossorigin="anonymous"></script>
Use it for CDNs in index.html.
18. How do you secure dynamic content rendered using Angular?
Avoid bypassing Angular sanitization. Use DomSanitizer only for trusted content. Example:
this.safe = this.sanitizer.bypassSecurityTrustHtml(userHtml);
Never use it on untrusted user input.
19. How can you prevent brute-force login attacks at the client level?
Implement client-side throttling and lockout logic. Example:
if (loginAttempts > 5) disableLoginButton();
Use CAPTCHA and server-side rate limiting for strong protection.
20. What strategies do you use for Angular dependency security management?
Audit dependencies regularly with npm audit. Example:
npm audit fix
Avoid unused packages, update regularly, and verify third-party libs.
21. How can you use a secure API gateway with an Angular frontend?
Route all API calls through the gateway and enforce SSL, RBAC, and throttling. Example:
this.http.get('/api/user') → handled via API Gateway
Gateway should validate tokens and forward requests.
Sai Reddy
saireddy-dotnetfs
22. How to implement CAPTCHA or reCAPTCHA in Angular forms?
Use Google reCAPTCHA API and add site key in the form. Example:
<re-captcha (resolved)="onCaptcha($event)"></re-captcha>
Verify CAPTCHA token on backend before login or signup.
23. How do you handle CORS in Angular apps during development and production?
Use Angular proxy for dev and configure server CORS headers in prod. Dev example:
"proxyConfig": "proxy.conf.json"
Server must allow Origin, Methods, and Headers.
24. How do you configure Angular for HTTPS-only communication?
Host Angular on an HTTPS server and redirect HTTP to HTTPS. Example:
In angular.json, set production URLs to https. Enforce HTTPS via .htaccess or Nginx.
25. What is the impact of lazy loading and how can it be secured?
Lazy loading improves performance but can expose routes if not secured. Always guard lazy routes.
Example:
{ path: 'admin', loadChildren: ..., canActivate: [RoleGuard] }
Never rely solely on frontend routing for protection.
Angular TypeScript Security Interview Questions and Answers for 7–15 years of experience
1. How do you architect a secure enterprise-grade Angular application?
Use modular architecture, lazy loading with guards, JWT + refresh token, and CSP.
Secure services via interceptors, implement RBAC at both route and component level.
Use SSO, 2FA, rate-limiting, error logging, and centralized state management (NgRx).
Enforce static analysis and dependency scanning in CI/CD.
2. What is the security consideration when building micro frontends with Angular?
Each micro frontend should have its own CSP, sanitization, and role enforcement.
Never share authentication state via global JS; use secure token communication.
Isolate execution contexts using Web Workers or Shadow DOM.
Use federated identity via OAuth2 or SSO to control session and access.
3. How do you enforce CSP (Content Security Policy) in Angular at scale?
Define CSP headers server-side to block inline scripts and styles. Example:
Content-Security-Policy: default-src 'self'; script-src 'self'
Avoid bypassSecurityTrust... unless absolutely needed. Use SRI for scripts.
4. How do you design a secure token-based authentication architecture with Angular and backend
APIs?
Use short-lived JWT tokens stored in memory and refresh tokens in HttpOnly cookies.
Access tokens are used with interceptors:
headers: { Authorization: `Bearer ${token}` }
Enforce token expiry, revocation, and rotation.
5. Explain Zero Trust Architecture in the context of Angular frontend.
Zero Trust assumes no implicit trust—even for internal networks.
Each request from Angular is authenticated and authorized with fine-grained RBAC.
Frontend should not trust stored tokens or roles—backend must validate.
Use secure tokens, device checks, and enforce MFA.
6. How would you audit Angular applications for security vulnerabilities?
Use npm audit, ESLint security rules, and OWASP ZAP for runtime testing.
Example:
npm audit fix
Also, run code linters for unsafe functions and dependency analyzers like Snyk.
Sai Reddy
saireddy-dotnetfs
7. How do you implement HMAC (Hash-based Message Authentication Code) with Angular and
APIs?
Generate HMAC signatures in backend using shared secret. Angular sends message:
headers: { 'X-Signature': hmacToken }
HMAC is not generated client-side to protect secret keys.
8. How do you secure communication between Angular apps and GraphQL endpoints?
Use HTTPS, query whitelisting, and token-based auth. Example:
httpOptions = { headers: new HttpHeaders({ Authorization: `Bearer ${token}` }) };
Avoid introspection and sanitize query params.
9. Explain how Angular handles XSS in different binding contexts (attribute, property, style, URL).
Angular escapes values based on context (e.g., [href], [style.background]).
Unsafe inputs are sanitized or blocked. Use DomSanitizer only for trusted data.
Example:
this.safeUrl = sanitizer.bypassSecurityTrustResourceUrl(url);
10. How do you protect a large Angular SPA from denial-of-service (DoS) attacks?
Use rate-limiting and request throttling server-side.
On Angular, debounce user inputs and limit data rendering. Example:
search.pipe(debounceTime(300))
Avoid loading large data sets without pagination.
11. How would you implement role and policy-based security models in Angular?
Define roles and permission policies in a service. Example:
canAccess(resource: string): boolean { return this.policies[role].includes(resource); }
Use in guards and UI templates to restrict access.
12. How do you integrate SSO (Single Sign-On) securely with Angular?
Use OAuth2/OpenID Connect with redirect flow. Angular handles callback:
this.oauthService.loadDiscoveryDocumentAndTryLogin();
Tokens are received and stored in memory or cookies.
13. How do you handle security in SSR (Server-Side Rendering) Angular apps?
Sanitize all rendered output, avoid leaking server secrets in pre-rendered HTML.
Use Helmet for HTTP headers, enforce CSRF tokens in forms.
Ensure API tokens are not embedded in HTML source.
14. What secure design patterns do you apply in Angular modules?
Use feature modules with lazy loading, strict type safety, and separation of concerns.
Apply guards at module routes and declare providers in forRoot() vs forChild().
Minimize shared state and expose minimal API from each module.
15. How do you ensure Angular component security in multi-team development?
Use strict lint rules, centralized sanitization utilities, and shared RBAC service.
Enforce input/output contracts via interfaces and shared libraries.
Secure component communication via services, not shared variables.
16. What strategies do you follow for secure state management (NgRx, Akita)?
Avoid storing tokens or PII in state. Use selectors to derive minimal needed info.
Protect store actions with auth checks. Example:
if (user.role === 'admin') store.dispatch(loadSensitiveData());
17. How do you manage secure data caching in Angular?
Use RxJS caching with in-memory or session-based TTL. Example:
shareReplay({ refCount: true, bufferSize: 1 })
Avoid storing sensitive data like tokens or user profile in localStorage.
Sai Reddy
saireddy-dotnetfs
18. How do you configure Angular CLI and Webpack to minimize security risks?
Enable production build optimizations:
ng build --prod
Use AOT, Terser for minification, and remove source maps from production.
19. How do you handle configuration and secret management in Angular deployments?
Do not store secrets in Angular code. Load runtime config via assets/config.json.
Backend injects secure env variables into config file at deploy time.
20. How can Angular apps prevent session fixation and hijacking attacks?
Avoid using predictable session IDs. Invalidate session on login/logout.
Use short token lifespans and store them in secure, non-persistent memory.
21. What security risks arise from using third-party Angular libraries, and how do you mitigate
them?
They may contain XSS/insecure code. Use trusted libraries, check licenses.
Example:
npm audit && npm ls library-name
Use npm shrinkwrap or package-lock.json for version control.
22. How would you secure a Progressive Web App (PWA) built with Angular?
Serve over HTTPS, validate service workers, and sanitize cached content.
Control caching via ngsw-config.json and validate payloads before storing.
23. How do you implement a secure CI/CD pipeline for Angular projects?
Run linting, testing, and npm audit on each commit. Example:
- run: npm audit
- run: ng lint && ng test --watch=false
Use secret management tools (e.g., Azure Key Vault, HashiCorp Vault).
24. What are the security implications of Angular Universal (SSR), and how to handle them?
SSR can leak server variables. Sanitize output and use XSS protection headers.
Avoid using DOM directly (not available in SSR). Validate all request data.
25. How do you ensure backward compatibility without introducing security flaws in enterprise
Angular apps?
Use API versioning and support legacy features via feature flags.
Never relax CSP, sanitization, or token policies to support old clients.
Test all fallback paths with security scenarios.
Sai Reddy
saireddy-dotnetfs
ReactJS Security Questions and Answers for 0–2 Years Experience (Beginner – Junior Level)
1. What is Cross-Site Scripting (XSS) and how does React protect against it?
XSS allows attackers to inject malicious scripts into web pages. React escapes content by default in
JSX, preventing XSS attacks unless developers use dangerouslySetInnerHTML.
<p>{userInput}</p> // Safe: React escapes HTML
Avoid directly injecting HTML unless sanitized. React’s default DOM escaping protects users.
4. What are props validation and how can they prevent security bugs?
Prop validation using PropTypes ensures components receive expected data types, avoiding
unintended behavior.
Component.propTypes = {
userId: PropTypes.number.isRequired
}
It prevents injection via malformed data and improves reliability. Helps catch bugs early during
development.
6. What is the difference between storing JWT tokens in localStorage vs. sessionStorage?
localStorage persists tokens across tabs and sessions, sessionStorage is cleared on tab close.
localStorage.setItem('token', token);
Both are accessible to JavaScript and vulnerable to XSS. Prefer secure, HttpOnly cookies when
possible.
Sai Reddy
saireddy-dotnetfs
8. What are React hooks and can they cause security issues?
Hooks like useEffect, useState manage state and side effects. They can cause security issues if used
improperly, like setting state from unvalidated input.
const [input, setInput] = useState('');
Always sanitize inputs and avoid calling APIs directly based on user input without validation.
11. What are higher-order components (HOCs) and can they help with access control?
HOCs wrap components to add features like authentication.
const withAuth = (Component) => (props) =>
isAuthenticated ? <Component {...props} /> : <Redirect to="/login" />;
They are reusable and help enforce access checks consistently.
14. What are HTTP interceptors and how can you secure requests in React?
In React, use Axios interceptors to attach tokens and handle responses.
axios.interceptors.request.use(config => {
config.headers.Authorization = `Bearer ${token}`;
return config;
});
Useful for adding auth headers and catching unauthorized responses globally.
Sai Reddy
saireddy-dotnetfs
Use SameSite, HttpOnly cookies, and CSRF tokens server-side.
React must follow secure patterns for cookies and form submissions.
19. What is the purpose of using Content Security Policy (CSP) with React apps?
CSP helps prevent XSS and data injection by controlling which sources are trusted.
Content-Security-Policy: default-src 'self'
Set this on your server. It blocks inline scripts and third-party code unless allowed.
Sai Reddy
saireddy-dotnetfs
24. Why is component reusability important for secure design?
Reusable components standardize input validation, access logic, and error handling.
Reduces chance of inconsistent security practices.
const SecureInput = ({ value, onChange }) => (
<input value={value} onChange={onChange} maxLength={100} />
);
Encourages DRY, testable and secure code.
25. What is the importance of HTTPS in React application deployment?
HTTPS encrypts data in transit, protecting sensitive information.
Browsers block features (like geolocation, service workers) on HTTP.
Always deploy React apps behind HTTPS to prevent MITM attacks.
Use SSL certificates and redirect HTTP to HTTPS.
React JS 3–6 Years Experience (Intermediate – Mid Level)
1. How do you implement role-based access control (RBAC) in React apps?
Create a central auth context to store user roles, then conditionally render UI or restrict routes.
if (user.role === 'admin') { return <AdminDashboard />; } else { return <AccessDenied />; }
Use guards in routes and protect sensitive components using role checks in context or HOCs.
2. How do you create a protected route component in React?
Create a wrapper around React Router's Route to verify auth before rendering.
const ProtectedRoute = ({ children }) => isAuth ? children : <Navigate to="/login" />;
Use this for all routes that require authentication to prevent unauthorized access.
3. What are the security implications of dangerouslySetInnerHTML and how to handle it?
It allows raw HTML injection, making it vulnerable to XSS attacks.
<div dangerouslySetInnerHTML={{ __html: sanitizedHtml }} />
Always sanitize HTML using libraries like DOMPurify before rendering to avoid executing malicious
scripts.
4. How do you manage and refresh JWT securely in React?
Store access tokens in memory or secure cookies and use refresh tokens via HttpOnly cookies.
When token expires, call backend refresh endpoint to get a new token.
axios.post('/refresh-token', {}, { withCredentials: true });
Avoid exposing refresh tokens to JavaScript.
5. What are the security risks of using third-party React components?
They may contain vulnerable code or open XSS vectors. Always review source, maintain updated
versions.
npm audit
Limit unnecessary dependencies and validate user input even in third-party components.
6. How do you prevent insecure direct object references (IDOR) in React?
Never rely solely on frontend data like IDs for authorization. Backend must verify ownership or
access.
GET /api/user/123 → Backend checks if requester owns ID 123
Hide sensitive data and validate access on server-side always.
7. How do you handle OAuth2/OIDC authentication flows in React?
Redirect users to the identity provider for login and handle callback with code/token.
window.location.href = `https://auth.com/oauth2/authorize?...`;
Use libraries like oidc-client and store tokens securely.
8. How can you securely implement logout functionality in React?
Clear tokens from memory or storage and call backend to invalidate refresh tokens.
localStorage.removeItem('token'); axios.post('/logout');
Sai Reddy
saireddy-dotnetfs
Redirect to login and ensure session termination on both client and server.
9. What is the difference between access token and refresh token, and how to handle both?
Access token is short-lived and used for API access, refresh token is long-lived and used to renew
access tokens.
Store refresh tokens in HttpOnly cookies, access tokens in memory or short-lived storage.
// Use refresh endpoint when 401 error occurs
Never expose refresh tokens to JavaScript.
10. How would you implement MFA/2FA in a React app?
Prompt user for OTP after password login, validate OTP on backend.
<input value={otp} onChange={handleChange} />
Use libraries like TOTP (Time-based One-Time Password) or external services like Authy or Google
Authenticator.
11. How do you prevent token theft or reuse in React apps?
Use short-lived access tokens, rotate refresh tokens, and store them in HttpOnly cookies.
Enforce IP/device checks on backend and logout sessions after reuse is detected.
logout(); // on token misuse
Implement CSRF protection and HTTPS.
12. What are the risks of client-side rendering (CSR) in React and how do you secure it?
Initial data exposure and longer time-to-render. Always validate data on backend and avoid exposing
secrets.
Don’t preload sensitive content or embed secrets in initial JS bundle.
Use SSR for better control and obfuscation.
13. How can you implement CSP in React apps during deployment?
Set CSP headers from server or meta tags to control allowed sources.
Content-Security-Policy: default-src 'self'; script-src 'self';
Avoid inline scripts and eval. Integrate with helmet in Node.js apps.
14. What is the role of react-helmet in improving security?
It allows setting secure HTTP headers and meta tags dynamically.
<Helmet><meta httpEquiv="Content-Security-Policy" content="default-src 'self'" /></Helmet>
Useful in SSR apps for per-page policies or meta security headers.
15. How do you securely handle file uploads in React?
Use input validation, size/type checks, and secure upload endpoints.
<input type="file" onChange={handleUpload} />
Upload directly to a backend or cloud service, don’t expose keys or process files in frontend.
16. How can you track and manage security vulnerabilities in npm dependencies?
Run npm audit, use snyk or OWASP Dependency-Check.
npm audit fix
Keep dependencies up to date and avoid using deprecated or unmaintained packages.
17. How do you prevent brute-force login attempts in React apps?
Limit login attempts on backend using rate limiting (e.g., express-rate-limit).
429 Too Many Requests
Add CAPTCHA after repeated failures and enforce strong password policies.
18. How can lazy loading impact the security of React applications?
Improperly lazy-loaded modules can expose sensitive functionality if URLs are guessed.
const Admin = React.lazy(() => import('./Admin'));
Protect routes with auth and roles even for lazy components.
Sai Reddy
saireddy-dotnetfs
19. How do you securely share data across React components?
Use context providers or state libraries and avoid putting sensitive data in global scope.
<AuthContext.Provider value={{ user }}>{children}</AuthContext.Provider>
Always fetch fresh data for critical views from secure APIs.
20. How do you handle expired tokens in a React SPA?
Detect 401 errors and call a refresh endpoint to renew the token.
axios.interceptors.response.use(..., error => { if (error.response.status === 401) refreshToken(); });
Redirect to login if refresh fails or token is revoked.
21. How do you handle CORS in React apps during development vs production?
In dev, use proxy in package.json or set CORS headers on backend.
"proxy": "http://localhost:5000"
In production, server must send appropriate Access-Control-Allow-Origin headers.
22. What are the risks of uncontrolled component rendering and how do you mitigate them?
It can lead to XSS or unauthorized data exposure. Sanitize inputs, validate props, and restrict
conditional rendering based on roles.
Use key props and memoization to prevent unnecessary re-renders.
Never render sensitive data before authentication.
23. How do you audit React apps for security?
Use static analysis tools like ESLint security plugins, dependency scanners, and manual code reviews.
npm audit && eslint --ext .js,.jsx src/
Test for known vulnerabilities and perform pen testing on endpoints.
24. How do you handle sensitive environment variables securely in React?
React builds expose env vars prefixed with REACT_APP_ and get embedded at build time.
const apiUrl = process.env.REACT_APP_API_URL;
Don’t store secrets; use backend to proxy sensitive logic securely.
25. How do you log security events without leaking user data in React?
Avoid logging PII or tokens in frontend logs. Use centralized logging services with redaction.
console.error("Login failed", { reason: error.message }); // no sensitive data
Log only metadata like timestamps, IPs, and status codes. Use server logs for detailed auditing.
Sai Reddy
saireddy-dotnetfs
5. How do you implement secure Single Sign-On (SSO) in React?
Integrate OAuth2/OIDC providers like Auth0 or Azure AD using libraries such as react-oidc-client.
Handle tokens securely, store refresh tokens in HttpOnly cookies, and implement silent renew.
userManager.signinRedirect();
6. How do you manage secrets/configuration securely in a CI/CD pipeline for React apps?
Use environment variables injected during build or deployment, avoid embedding secrets in client
code. Store secrets in vaults (HashiCorp, AWS Secrets Manager). Use runtime config or proxy
sensitive calls to backend.
7. How do you secure React micro frontends in a large application landscape?
Isolate micro frontends with separate origins or iframe sandboxing, enforce CSP, authenticate each
independently, and share auth state securely via secure cookies or OAuth tokens.
8. How would you handle SSR (Server-Side Rendering) security in React (e.g., with Next.js)?
Sanitize server-rendered content, avoid exposing secrets in getServerSideProps. Use CSP headers,
secure cookies, and prevent data leakage by controlling cache headers.
export async function getServerSideProps(context) { /* no secrets here */ }
9. How do you design a secure token handling architecture across tabs/windows in React?
Store access token in memory or secure storage; use BroadcastChannel or localStorage events to
sync logout or token refresh across tabs.
const bc = new BroadcastChannel('auth');
bc.postMessage('logout');
10. How do you enforce application-wide security policies (e.g., CSP, SRI) for React?
Configure web server to send CSP headers, use Subresource Integrity (SRI) for external scripts. Use
react-helmet to dynamically set security headers.
<Helmet><meta httpEquiv="Content-Security-Policy" content="default-src 'self'" /></Helmet>
11. How do you prevent session fixation or hijacking attacks in React apps?
Use HttpOnly secure cookies for tokens, regenerate session IDs on login, use SameSite cookies,
implement token rotation, and log out users on suspicious activity.
12. What are the risks of using React with legacy backends and how do you secure them?
Legacy backends might lack proper auth or input validation. Secure by adding API gateways,
validating input/output, sanitizing data, and upgrading protocols (e.g., use HTTPS and OAuth).
13. How do you handle security for offline support in a PWA React application?
Cache only non-sensitive data with service workers, avoid caching auth tokens, encrypt stored data if
needed, and clear caches on logout or token expiration.
14. How do you ensure secure data flow across Redux or Context API?
Never store sensitive tokens or PII in Redux; keep it ephemeral or encrypted if needed. Validate all
data before use and implement middleware for sanitization and access control.
15. How do you ensure data encryption and decryption in React-based frontend apps?
Perform encryption on backend or use Web Crypto API for client-side encryption if necessary. Avoid
storing unencrypted sensitive data locally.
const encrypted = await crypto.subtle.encrypt(...);
16. How do you handle user impersonation and audit logging securely in React?
Implement backend support for impersonation with audit trails. React frontend shows clear UI
indicators, logs actions securely without sensitive info, and requires re-authentication.
17. How do you track and eliminate vulnerable transitive dependencies in React projects?
Use tools like npm audit, Snyk, or Dependabot for automated vulnerability scanning and patching.
Lock dependencies using package-lock.json or yarn.lock.
Sai Reddy
saireddy-dotnetfs
18. How do you prevent React SSR content leakage via cache or headers?
Set strict Cache-Control headers to prevent caching sensitive pages, use Vary headers, and sanitize
server-rendered content. Avoid embedding secrets in SSR props.
19. How do you isolate React apps in a containerized or cloud-native environment for security?
Use container security best practices: least privileges, network segmentation, secrets management,
vulnerability scanning, and automated security policies with Kubernetes or Docker.
20. How do you deal with security when implementing dynamic imports or code-splitting in React?
Validate and sanitize dynamic import paths, protect lazy-loaded routes with auth guards, and avoid
exposing sensitive code to unauthorized users.
21. How do you prevent malicious code injection via runtime configuration in React apps?
Validate and sanitize all runtime config inputs, avoid eval or dynamic code execution, and enforce
CSP policies to block inline scripts.
22. What steps would you take to perform a React security audit for a fintech project?
Review auth flows, token handling, dependency vulnerabilities, input sanitization, data exposure,
CSP, session management, and compliance with regulations like PCI-DSS.
23. How do you enforce strict type-checking and linting to avoid security bugs in React?
Use TypeScript for strong typing, ESLint with security rules/plugins, Prettier for code formatting, and
enforce these in CI pipelines to catch issues early.
24. How do you manage secure version upgrades in React for enterprise environments?
Test upgrades in staging, audit changelogs for breaking/security changes, use canary releases,
automate dependency updates, and maintain backward compatibility.
25. How do you enforce security across teams working on a large monorepo React project?
Implement centralized security guidelines, shared linting and type rules, automated code scans, peer
reviews, and continuous training. Use CI/CD gates for security compliance.
Sai Reddy
saireddy-dotnetfs