DEV Community

Cover image for Protecting My React + express API with unkey 🔑
Adil Kadival
Adil Kadival

Posted on

Protecting My React + express API with unkey 🔑

What is unkey ?

Unkey is a developer-friendly API key management tool that provides a secure and straightforward way to authenticate requests and manage access permissions. It lets developers focus on their app while Unkey takes care of protecting endpoints and managing rate limits.

unkey

A best Thing about Unkey which I loves really it's support multiple Languages with multiple Frameworks 🎉🎉
You can see here it's all template

I have create one project with unkey using react and express, I feel it is really easy to use and implement in a project.

my project

In this Post, I'll share that how:

  1. Set up Unkey in our app.
  2. Basic Setup of Express and react App.
  3. Use middleware for securing protected routes.
  4. Share insights and outcomes based on our experience.

1. Setting Up Unkey in Your App

To get started with Unkey, sign up on unkey.com, where you’ll receive an API Root Key and API ID. We’ll use these credentials to set up authentication in our app.

Install Unkey SDK
In your project directory, install the Unkey SDK to simplify API key verification and permissions management:

npm install @unkey/api dotenv

Enter fullscreen mode Exit fullscreen mode

Configure environment variables in your .env file to store your Unkey credentials securely:

UNKEY_ROOT_KEY=your_unkey_root_key
UNKEY_API_ID=your_unkey_api_id
Enter fullscreen mode Exit fullscreen mode

2. Basic Setup of Express App

Here’s a basic setup for our Express server, which includes a public endpoint accessible to all users and a protected endpoint that only authorized users can access.

import express from "express";
import withAuth from "./middlewares/authentication.js";
import dotenv from "dotenv";
import bodyParser from "body-parser";
import cors from "cors";

dotenv.config();

const app = express();
const port = process.env.PORT || 3000;

app.use(express.json());
app.use(bodyParser.json());
app.use(cors());

// Public route
app.get("/public", (req, res) => {
  res.send("This page is accessible to everyone.");
});

// Protected route
app.get(
  "/protected",
  withAuth({ permission: "call-protected-route" }),
  (req, res) => {
    res.send("This is protected data, accessible only with proper permissions.");
  }
);

app.listen(port, () => {
  console.log(`App listening at http://localhost:${port}`);
});

Enter fullscreen mode Exit fullscreen mode

react setup

const [adminData, setAdminData] = useState([]);
  console.log(adminData);
  const [error, setError] = useState(null);

  const fetchAdminData = async () => {
    try {
      const response = await axios.get("http://localhost:5555/protected", {
        headers: { Authorization: `Bearer <your unkey api id>` },
      });
      setAdminData(response.data);
    } catch (err) {
      setError(`Error fetching admin data: ${err.message}`);
    }
  };

  useEffect(() => {
    fetchAdminData();
  }, []);
Enter fullscreen mode Exit fullscreen mode

3. Implementing the Unkey Middleware for Authentication

Our withAuth middleware verifies API keys and checks if the requesting user has the necessary permissions.

Middleware Code for Authorization
In middlewares/authentication.js, we import and configure Unkey:

import { Unkey } from "@unkey/api";
import dotenv from "dotenv";

dotenv.config();

function withAuth(opts) {
  const unkey = new Unkey({
    rootKey: process.env.UNKEY_ROOT_KEY,
  });

  return async (req, res, next) => {
    const key = req.headers["authorization"]?.split(" ").at(1);
    if (!key) {
      console.log("No API key found");
      res.status(401);
      return res.send("Unauthorized");
    }

    const { result, error } = await unkey.keys.verify({
      apiId: process.env.UNKEY_API_ID,
      key,
      authorization: { permissions: opts.permission },
    });

    if (error) {
      console.error("Verification error:", error.message);
      res.status(500);
      return res.send("Internal Server Error");
    }

    if (!result.valid) {
      console.log("Forbidden:", result.code);
      res.status(403);
      return res.send("Forbidden");
    }

    next();
  };
}

export default withAuth;

Enter fullscreen mode Exit fullscreen mode

This middleware does the following:

  • Retrieves the API key from the Authorization header.
  • Verifies the key and checks for specific permissions.
  • If verification fails, it returns a 403 Forbidden status. If no API key is provided, it returns 401 Unauthorized.

4. Conclusion and Outcome

Benefits of Using Unkey

1. Enhanced Security: Unkey provides a robust mechanism to protect sensitive API endpoints by verifying API keys and permissions.

2. Scalable Authorization: With permission-based control, access management becomes efficient and scalable.

3. Developer-Friendly: Unkey’s simple integration process and detailed documentation made the setup process straightforward.

Key Learnings

API Security is critical in today’s applications, and tools like Unkey simplify the process.

Rate Limiting and Access Control can protect backend resources while improving the overall user experience.

Final Thoughts

Integrating Unkey in your application can help ensure that only authorized users access sensitive data, improving the security of your APIs. If you’re looking for a streamlined way to manage API keys and permissions, Unkey is an excellent choice for fast, reliable, and secure key management.

Visit Unkey to learn more about their services and sign up for your API key today!

Thanks for Reading 🎉🎉
best regards

Adil kadival (K-adi)

Top comments (0)