affaan-m/ECC · error
Unauthorized
Error message
Unauthorized
What it means
The withAuth middleware from the backend-patterns skill wraps Next.js API handlers: it reads req.headers.authorization, strips the 'Bearer ' prefix, and if the result is falsy it short-circuits with 401 { error: 'Unauthorized' }. This specific message means no bearer token reached the handler at all — the 'Invalid token' variant covers tokens that were present but failed verification.
Source
Thrown at skills/backend-patterns/SKILL.md:111
})
}
private async vectorSearch(embedding: number[], limit: number) {
// Vector search implementation
}
}
```
### Middleware Pattern
```typescript
// Request/response processing pipeline
export function withAuth(handler: NextApiHandler): NextApiHandler {
return async (req, res) => {
const token = req.headers.authorization?.replace('Bearer ', '')
if (!token) {
return res.status(401).json({ error: 'Unauthorized' })
}
try {
const user = await verifyToken(token)
req.user = user
return handler(req, res)
} catch (error) {
return res.status(401).json({ error: 'Invalid token' })
}
}
}
// Usage
export default withAuth(async (req, res) => {
// Handler has access to req.user
})
```
View on GitHub (pinned to d8409a4b08)
Solutions
- Attach the header: Authorization: Bearer <token> on every request to the wrapped route
- Verify the token is actually retrieved from storage before the request fires (await the auth client / check the session is loaded)
- If a proxy sits in front, confirm it forwards the Authorization header and CORS allows it (Access-Control-Allow-Headers)
- Check header spelling — the middleware only reads req.headers.authorization
Example fix
// before
await fetch('/api/protected', { method: 'GET' }) // 401 Unauthorized
// after
await fetch('/api/protected', {
headers: { Authorization: `Bearer ${token}` },
}) Defensive patterns
Strategy: validation
Validate before calling
// Client: only fire when a token is actually in hand
function authHeaders(token: string | null | undefined): HeadersInit {
if (!token) throw new Error('No auth token available — complete login before calling protected routes')
return { Authorization: `Bearer ${token}` }
} Type guard
const hasBearerToken = (h: Headers | Record<string, string>): boolean => {
const v = h instanceof Headers ? h.get('authorization') : h['Authorization'] ?? h['authorization']
return typeof v === 'string' && v.trim().length > 0
} Prevention
- Centralize authenticated fetch in one client that always attaches the Authorization header
- Gate protected UI/actions on session state so requests cannot fire pre-login
- When a proxy or CORS layer is involved, verify Authorization survives: allow it in Access-Control-Allow-Headers and proxy config
- Remember the distinction: 'Unauthorized' (401) = header missing; 'Invalid token' (401) = header present but failed verification
When it happens
Trigger: Calling the protected route with no Authorization header; sending the token under the wrong header name (x-api-key instead of Authorization); an empty Authorization header; a corporate proxy or misconfigured CORS setup stripping the Authorization header; fetch call that forgot to attach headers.
Common situations: Frontend not yet storing the token (request fired before login completed); auth header dropped by a gateway/reverse proxy; CORS preflight not allowing the Authorization header so the browser omits it; curl test without -H 'Authorization: Bearer ...'.
Understand the failure class
- Authentication and authorization failures — expired tokens, bad credentials, and missing scopes.
Related errors
- Invalid token
- ${command} ${args.join(' ')} failed: ${(result.stderr || res
- ${command} ${args.join(' ')} failed: ${(result.stderr || res
- VALIDATION_ERROR
- INTERNAL_ERROR
AI-assisted analysis of affaan-m/ECC@d8409a4b08 (2026-08-26).
Data as JSON: /api/errors/337bfdd06fa6fe1a.
Report an issue: GitHub.