<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Adil Kadival </title>
    <description>The latest articles on DEV Community by Adil Kadival  (@k-adi).</description>
    <link>https://dev.to/k-adi</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1477351%2Fea88bf04-6cc7-402b-9434-5c8cc5dea7e1.png</url>
      <title>DEV Community: Adil Kadival </title>
      <link>https://dev.to/k-adi</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/k-adi"/>
    <language>en</language>
    <item>
      <title>Protecting My React + express API with unkey 🔑</title>
      <dc:creator>Adil Kadival </dc:creator>
      <pubDate>Tue, 29 Oct 2024 10:53:46 +0000</pubDate>
      <link>https://dev.to/k-adi/protecting-my-react-express-api-with-unkey-3lbl</link>
      <guid>https://dev.to/k-adi/protecting-my-react-express-api-with-unkey-3lbl</guid>
      <description>&lt;h2&gt;
  
  
  What is unkey ?
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://www.unkey.com" rel="noopener noreferrer"&gt;Unkey&lt;/a&gt; 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.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Farrow9qwtx2qyk50cq6b.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Farrow9qwtx2qyk50cq6b.png" alt="unkey" width="800" height="379"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A best Thing about Unkey which I loves really it's support multiple Languages with multiple Frameworks 🎉🎉&lt;/strong&gt;&lt;br&gt;
&lt;em&gt;You can see here it's all &lt;a href="https://www.unkey.com/templates" rel="noopener noreferrer"&gt;&lt;strong&gt;template&lt;/strong&gt;&lt;/a&gt;&lt;/em&gt; &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;I have create one &lt;a href="https://github.com/adilkadivala/unkey_project" rel="noopener noreferrer"&gt;project&lt;/a&gt; with unkey using react and express, I feel it is really easy to use and implement in a project.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnho7uvo6k19zdgyvvhh0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnho7uvo6k19zdgyvvhh0.png" alt="my project" width="800" height="217"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In this Post, I'll share that how:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Set up Unkey in our app.&lt;/li&gt;
&lt;li&gt;Basic Setup of Express and react App.&lt;/li&gt;
&lt;li&gt;Use middleware for securing protected routes.&lt;/li&gt;
&lt;li&gt;Share insights and outcomes based on our experience.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;1.&lt;/strong&gt; &lt;em&gt;Setting Up Unkey in Your App&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.unkey.com/docs/libraries/ts/sdk/overview" rel="noopener noreferrer"&gt;Install Unkey SDK&lt;/a&gt;&lt;br&gt;
In your project directory, install the Unkey SDK to simplify API key verification and permissions management:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install @unkey/api dotenv

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Configure environment variables in your .env file to store your Unkey credentials securely:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;UNKEY_ROOT_KEY=your_unkey_root_key
UNKEY_API_ID=your_unkey_api_id
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2.&lt;/strong&gt; &lt;em&gt;Basic Setup of Express App&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;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.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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) =&amp;gt; {
  res.send("This page is accessible to everyone.");
});

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

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

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;react setup&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [adminData, setAdminData] = useState([]);
  console.log(adminData);
  const [error, setError] = useState(null);

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

  useEffect(() =&amp;gt; {
    fetchAdminData();
  }, []);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3.&lt;/strong&gt; &lt;em&gt;Implementing the Unkey Middleware for Authentication&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Our withAuth middleware verifies API keys and checks if the requesting user has the necessary permissions.&lt;/p&gt;

&lt;p&gt;Middleware Code for Authorization&lt;br&gt;
In middlewares/authentication.js, we import and configure Unkey:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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) =&amp;gt; {
    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;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This middleware does the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Retrieves the API key from the Authorization header.&lt;/li&gt;
&lt;li&gt;Verifies the key and checks for specific permissions.&lt;/li&gt;
&lt;li&gt;If verification fails, it returns a 403 Forbidden status. If no API key is provided, it returns 401 Unauthorized.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;4.&lt;/strong&gt; &lt;em&gt;Conclusion and Outcome&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Benefits of Using Unkey&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Enhanced Security&lt;/strong&gt;: Unkey provides a robust mechanism to protect sensitive API endpoints by verifying API keys and permissions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Scalable Authorization&lt;/strong&gt;: With permission-based control, access management becomes efficient and scalable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Developer-Friendly&lt;/strong&gt;: Unkey’s simple integration process and detailed documentation made the setup process straightforward.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Key Learnings&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;API Security is critical in today’s applications, and tools like Unkey simplify the process.&lt;/p&gt;

&lt;p&gt;Rate Limiting and Access Control can protect backend resources while improving the overall user experience.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Final Thoughts&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;Visit &lt;a href="https://www.unkey.com" rel="noopener noreferrer"&gt;Unkey&lt;/a&gt; to learn more about their services and sign up for your API key today!&lt;/p&gt;

&lt;p&gt;Thanks for Reading 🎉🎉&lt;br&gt;
best regards&lt;/p&gt;

&lt;p&gt;Adil kadival (&lt;a href="https://github.com/adilkadivala" rel="noopener noreferrer"&gt;K-adi&lt;/a&gt;)&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
