Oamar Kanji
Oamar Kanji

Reputation: 2224

What is the best way to make a request from a node express app to a third party api that requires its own authentication?

I have a node express app that uses keycloak authentication to secure all API endpoints. Express middleware has been set up for authentication to make sure that each incoming request from the front end has the appropriate keycloak token. I need to make a post request from my node app to a third party backend API to subscribe users to an email service that uses a different authentication method which my middleware would not work with.

What would be the best practice for making a request from the third party API? I am considering creating a new express instance and use a separate middleware specific for that post request. Is this an ok thing to do or is there a better way?

Here is a simplified version of my node app. See the

index.js

import { authmware } from "./authmware";
import express from "express";
import { router } from "./router";

const app = express();
authmware(app);
router(app);

app.use((err, req, res, next) => {
  logger.error(err.message);
  const code = err.code ? err.code : 500;
  const message = err.message ? err.message : "Internal Server Error";

  res.status(code).json({ error: message, success: false });
});

export default app;

router.js

import express from "express";
import createProfile from "../../controllers/createProfile";
    
const router = express.Router();
    
router.post("/", createProfile);
    
export const router = (app) => {
   app.use("/api/v1/createProfile", router);
};

controllers/createProfile.js

const createProfile = async (req, res) => {

  // ... Do some stuff

  // ** make request to a different api here ** 
  await makeThirdPartyApiRequest();

}

How would I make this third party api request that uses a different style of authentication?

Upvotes: 1

Views: 500

Answers (1)

Yusufali2205
Yusufali2205

Reputation: 1372

This is a very common use case. You can use 10 third party APIs in your node server and all having different authentication mechanisms irrespective of the auth you are using for your client requests.

await makeThirdPartyApiRequest();
  // http request to API
  // attach proper auth headers (API key / jwt / basic auth / oAuth token). This will be based on the authentication method the API is offering.
}

Update based on your recent comment:

The API should have some documentation on how to authenticate using the user key and secret key. For example: Google APIs just require you to send API key with request https://cloud.google.com/api-keys/docs/overview

Upvotes: 3

Related Questions