epam / epam/statgpt-admin-frontend
[Perf Improvement] CSP Header Re-Generated on Every Request (Middleware + Config)
- Dominant language
- TypeScript
- Stars
- 18
- Forks
- 0
- Avg merge
- 15h 5m
- Merged PRs (30d)
- 19
Description
### StatGPT Admin Frontend version
0.4.5
### What is the problem this feature will solve?
- **Where:** `src/proxy.ts` and `apps/statgpt-admin-frontend/next.config.js`
- **Why:** Both middleware and next.config generate identical CSP headers with `crypto.randomUUID()` on every request. The nonce value changes per-request but is duplicated across two execution paths, and the string manipulation (`replace(/\s{2,}/g, ' ')`) runs redundantly.
- **Impact:** CPU overhead on every request (both SSR and API routes); prevents effective caching of header values.
### What is the feature you are proposing to solve the problem?
**Potential Fix:**
1. **Generate nonce once at request time** in middleware and pass it via header to next.config (or env).
2. **Move CSP header building to a shared utility** to avoid duplication:
```typescript
// lib/csp.ts
export function buildCSPHeader(nonce: string): string {
return `
default-src 'self';
script-src 'self' 'nonce-${nonce}' 'strict-dynamic' https: http: ${
process.env.NODE_ENV === 'production' ? '' : `'unsafe-eval'`
};
style-src 'self' https://cdn.jsdelivr.net 'unsafe-inline';
...
`.replace(/\s{2,}/g, ' ').trim();
}
```
3. **Pre-compile CSP string template** at build time (CSP directives don't change per request), only inject nonce dynamically.
**Validate:**
- Run `npm run build` and check output size (`dist/apps/statgpt-admin-frontend/.next/server/pages/_middleware.js`).
- Profile middleware execution time with DevTools or server logs.
- Check for repeated CSP string construction in flame graphs.
Contributor guide
Research direction
Compare CSP generation in src/proxy.ts and apps/statgpt-admin-frontend/next.config.js, then inspect how middleware and Next.js configuration share headers. Run npm run build and check dist/apps/statgpt-admin-frontend/.next/server/pages/_middleware.js; done means CSP generation is not duplicated unnecessarily while nonce behavior remains correct and build output and profiling can be compared.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- next.js, typescript
- Domain
- frontend, performance
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 55/100