---
title: "Secure Moleculer APIs with API Key Authentication"
description: "Secure your Moleculer API using a shared secret."
canonicalUrl: "https://zuplo.com/use-cases/api-key-auth/javascript/moleculer/secure-header"
framework: "Moleculer"
language: "JavaScript"
authStrategy: "shared secret header"
pageType: use-case
---

# Secure Moleculer APIs with API Key Authentication

Secure your Moleculer API using a shared secret.

## How Zuplo Handles It

Put Zuplo in front of your Moleculer backend to authenticate API keys and forward a shared secret header so your origin only accepts traffic from Zuplo.

## Moleculer Backend Code

```javascript
const { ServiceBroker } = require("moleculer");
const crypto = require("crypto");

const SharedSecretMiddleware = {
  name: "SharedSecretMiddleware",
  localEvent: {
    $beforeCall: function (ctx, eventName, params) {
      const secret = ctx.meta.headers["x-shared-secret"];
      const expectedSecret = process.env.SHARED_SECRET;

      if (!expectedSecret) {
        throw new Error("Server configuration error");
      }

      if (!secret) {
        throw new Error("No secret provided");
      }

      if (
        secret.length !== expectedSecret.length ||
        !crypto.timingSafeEqual(
          Buffer.from(secret),
          Buffer.from(expectedSecret),
        )
      ) {
        throw new Error("Invalid secret");
      }
    },
  },
};

const broker = new ServiceBroker({
  middlewares: [SharedSecretMiddleware],
});

broker.createService({
  name: "api",
  actions: {
    protectedAction: {
      handler(ctx) {
        return { message: "Access granted" };
      },
    },
  },
});

broker.start();
```

## Example Request

```bash
curl -X GET \
  'https://your-api.zuplo.dev/your-route' \
  -H 'Authorization: Bearer YOUR_API_KEY'
```

## Learn More

- [API Key Authentication on Zuplo](https://zuplo.com/docs/policies/api-key-auth-inbound)
- [JWT Authentication on Zuplo](https://zuplo.com/docs/policies/open-id-jwt-auth-inbound)
- [All use cases](https://zuplo.com/use-cases)
