Node.js API Authentication with API Keys
In this tutorial, we will create a Node.js API and implement an authentication system using API keys. We’ll cover the benefits of using API keys, how to generate them, and how to authenticate requests.
Benefits of Using API Keys
API keys offer several advantages over other authentication methods:
- Easy to Implement: API keys are simple to generate and verify.
- Flexibility: API keys can be used for various authentication scenarios, such as limiting access to specific routes or tracking usage.
- Security: API keys are resistant to common web attacks like cross-site scripting (XSS) and cross-site request forgery (CSRF).
Initial Project Setup
Create a new Node.js project by running npm init
in your terminal. Then, install the required dependencies:
bash
npm install express nodemon
Create a new file called package.json
and add the following script:
json
"scripts": {
"start": "nodemon server.js"
}
Generating API Keys
Create a new file called apiAuth.js
and add the following code:
“`javascript
function genAPIKey() {
const apiKey = Math.random().toString(36).substr(2, 30);
return apiKey;
}
module.exports = { genAPIKey };
“`
This function generates a random API key using the Math.random()
method and converts it to a base-36 string.
Creating User Data
Create a new file called initialData.js
and add the following code:
“`javascript
const users = [];
module.exports = { users };
“`
This file will store our user data.
Registering Users
Create a new function in apiAuth.js
to register users:
“`javascript
function createUser(username) {
const apiKey = genAPIKey();
const user = { username, apiKey, usageCount: 0 };
users.push(user);
return user;
}
module.exports = { createUser };
“`
This function generates a new API key, creates a new user object, and adds it to the users
array.
Authenticating Requests
Create a new function in apiAuth.js
to authenticate requests:
“`javascript
function authenticateKey(apiKey) {
const user = users.find((user) => user.apiKey === apiKey);
if (!user) {
return false;
}
user.usageCount++;
return true;
}
module.exports = { authenticateKey };
“`
This function finds the user with the matching API key and increments their usage count.
Server Routes
Create a new file called server.js
and add the following code:
“`javascript
const express = require(“express”);
const app = express();
const { createUser, authenticateKey } = require(“./apiAuth”);
app.post(“/register”, (req, res) => {
const username = req.body.username;
const user = createUser(username);
res.json(user);
});
app.get(“/data”, (req, res) => {
const apiKey = req.header(“x-api-key”);
if (!authenticateKey(apiKey)) {
res.status(401).send(“Invalid API key”);
return;
}
// Send data
});
app.listen(3000, () => {
console.log(“Server started on port 3000”);
});
“`
This code sets up two routes: one to register a new user and another to retrieve data using an API key.
Testing
Start the server by running npm start
. Then, use a tool like curl
to test the API endpoints:
“`bash
curl -X POST -H “Content-Type: application/json” -d ‘{“username”: “john”}’ http://localhost:3000/register
curl -X GET -H “x-api-key:
“`
Replace <api-key>
with the actual API key returned from the registration endpoint.
That’s it! You now have a basic Node.js API with API key authentication.