Express request object that may contain Authorization header
Express response object (unused)
Express next function to continue middleware chain
Promise that resolves when optional authentication is complete
// Public endpoint with optional personalization
router.get('/courses', optionalAuth, (req, res) => {
if (req.user) {
// Return personalized course recommendations
return res.json(getPersonalizedCourses(req.user.sub));
}
// Return public course list
return res.json(getPublicCourses());
});
// Content that shows different information for authenticated users
router.get('/lessons/:id', optionalAuth, (req, res) => {
const lesson = getLessonById(req.params.id);
if (req.user) {
// Include user progress and personalized hints
lesson.progress = getUserProgress(req.user.sub, req.params.id);
lesson.hints = getPersonalizedHints(req.user.sub);
}
res.json(lesson);
});
// API endpoint that works for both public and authenticated access
router.get('/search', optionalAuth, (req, res) => {
const results = searchContent(req.query.q);
if (req.user) {
// Add user-specific ranking and filtering
results.forEach(result => {
result.relevanceScore = calculatePersonalizedScore(result, req.user);
});
}
res.json(results);
});
Optional Authentication Middleware
Provides optional authentication that attaches user information to the request if a valid JWT token is present, but allows the request to continue even without authentication. This middleware is useful for endpoints that provide different content or functionality based on whether a user is authenticated.
Unlike authenticateToken, this middleware does not throw errors for missing or invalid tokens. Instead, it silently ignores authentication failures and continues processing. This allows endpoints to serve both public and personalized content based on authentication status.
The middleware is ideal for public endpoints that can provide enhanced functionality for authenticated users, such as personalized course recommendations or user-specific progress information while still serving basic content to anonymous users.