Blog>
Snippets

Protecting API Routes

Illustrate the protection of API routes with authentication checks, returning different data or error messages based on the user's logged-in state.
function isAuthenticated(req) {
  // Mock function to check if user is authenticated
  // Replace this with real authentication logic, e.g. checking a JWT token
  return req.user && req.isAuthenticated;
}

function protectRoute(req, res, next) {
  if (!isAuthenticated(req)) {
    res.status(401).json({ error: 'User not authenticated' });
    return;
  }
  next();
}
A Javascript function that checks if the request comes from an authenticated user. If not, it responds with an HTTP 401 status and an error message. This is a middleware function for use with a Node.js server.
const express = require('express');
const app = express();

app.get('/protected-route', protectRoute, (req, res) => {
  // This route is now protected with the 'protectRoute' middleware
  // Only authenticated users can access this
  res.json({ data: 'Sensitive data' });
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});
An example using Express.js to create a server with a protected API route. The '/protected-route' endpoint uses the 'protectRoute' middleware to ensure only authenticated users can access it.
body {
  background-color: #f4f4f4;
}

.hidden {
  display: none;
}
Simple CSS to set the background color of the page and to hide elements with the 'hidden' class, which can be used to conceal parts of the UI until the user is authenticated.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Protected API Route Example</title>
  <style>
    /* Include the CSS code from above here */
  </style>
</head>
<body>
  <div id="protected-content" class="hidden">
    <p>This content is only visible to authenticated users</p>
  </div>
  <script>
    // Include the JavaScript code from above here
  </script>
</body>
</html>
An HTML template that contains a hidden div which is supposed to display protected content. It should become visible once the user has been authenticated with the JavaScript logic provided.