Optional Authentication
🧠 Backend concept I learned today that changed how I design APIs:
👉 Optional Authentication
Most people think APIs are either:
❌ Public
❌ Protected
But there’s a third type 👀
🔥 Optional Auth:
✔ Anyone can access
✔ BUT if logged in → return extra data
📌 Example (coding platform):
GET /problems/:slug
Get Chirag Kashyap’s stories in your inbox
Join Medium for free to get updates from this writer.
Logged out:
→ show problem + starter code
Logged in:
→ show problem + user’s saved code
💡 Same API, different experience
⚡ Why this is powerful:
✔ No multiple API calls
✔ Cleaner frontend
✔ Better UX
✔ Scales like real products
Used in:
LeetCode, GitHub, Twitter, Notion 👀
🧠 Key idea:
“Don’t block users — enhance experience if they are logged in”
This one concept made my backend feel 10x cleaner 😤
Example —
export const optionalAuth = (req, res, next) => {
try {
const token = req.cookies.token;
if (token) {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
}
} catch (err) {
// intentionally empty
}
next();
};



