Securing and Logging APIs
Introduction: Why Secure and Log Your API?
Welcome back! So far, you have learned how to organize your backend code using a service layer and how to validate data in your Task Manager API. Now, it’s time to make your API more secure and easier to monitor.
APIs are often exposed to the internet, which means anyone can try to access them. Without security, someone could misuse your API or access sensitive data. Logging is also important because it helps you see what’s happening in your API — who is using it, when, and how. This is useful for debugging and for keeping your API safe.
In this lesson, you will learn how to:
- Protect your API using an API key.
- Log every request to your API for better monitoring.
By the end, your Task Manager API will be more secure, and you’ll have a record of every request made to it.
Your Current Backend Structure
Before adding logging and API key security, let’s review how your current backend is structured:
- You have API routes under
/api/tasks, which call functions from your taskService to interact with an in-memory array of tasks. - All task-related routes (GET, POST, PUT, PATCH, DELETE) are already implemented in
route.tsfiles using the service layer. - Now, we’ll add middleware that runs before any of these routes are handled to:
- Check for a valid API key in the request.
- Log information about every request for debugging and security. This mirrors how real-world APIs typically handle request-level authentication and monitoring.
Adding API Key Authentication With Middleware
To protect your API, you can require clients to include a special key (an API key) in their requests. Only requests with the correct key will be allowed.
In Next.js, you can use middleware to check for this key. Here’s how you can do it:
Explanation:
- The
middlewarefunction runs before your API routes. - It checks if the request path starts with
/api/tasks. From the previous courses we know that we can change this logic to protect any other paths in your API — for example, if you add/api/adminin the future. For now, we're securing just the/api/tasksendpoints. - If it does, it looks for an
x-api-keyheader in the request. - If the key is missing or incorrect, it returns a 401 Unauthorized response. In production, you'd typically use a longer and more secure key — and rotate it periodically. You may also want to log these unauthorized attempts for auditing and alerting.
- If the key is correct, the request continues.
Storing the API Key:
You should never hard-code secrets in your code. Instead, use environment variables. In your .env.local file, add:
This keeps your secret key safe and out of your codebase.
💡 Debug Tip: If your middleware isn't working or always returns
Unauthorized, double-check:
- That the key in
.env.localexactly matches what’s being typed in the input.- That the middleware file is named exactly
middleware.tsand placed insrc/.- That you restarted the server after changing
.env.local.
