Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make get request to third party API with api key using express.router();

I am building a react app, and in it I am retrieving data from a third party site which requires me to send the API key in the header using 'X-Auth-Token'.

Currently I am making this request using fetch() api from the clientside js files. I understand this is bad practice and I should hide my api key, so this is what I am trying to do but am finding it hard to understand how all the components fit together in this puzzle...

I have followed a tutorial and now have a create-react-app project listening locally on port 3000, and an express server (using express.router()) listening locally on port 9000.

I want to make the api request to the third party from the express server, and then send that to the front end.

  1. using express.router(), how would i make a request to a third party that includes my api key, and then send that on to the front end?
  2. when i eventually host this project (i am hosting on heroku), instead of the front end making a fetch request to port9000 to retrieve the data from the express server request, what url should it be listening to? - I think i lack understanding when it comes to this part.
like image 958
Jonny Avatar asked Oct 22 '25 06:10

Jonny


1 Answers

You are on point, you should use like a middleman to retrive your data to your frontend. There are couple of implementation of course. Personally I like the serverless approach, using AWS lambda functions for it. But back to your approach. I would retrive the data using probably the axios module, very easy and straightforward. You can pass the x-auth-token header to the instance


const express = require('express');
const axios = require('axios');

const app = express()

const axiosInstance = axios.create({
    baseURL: '<some-domain>',
    headers: { 'X-Auth-Token' : '<some-token>'}
});

app.get('/data', async(req, res, next) => {
    try {
        const response = await axiosInstance.get('/<path>');
        // process your data and send back to the user
    } catch (error) {
        // handle if you got an error
    }
})

It is just a showcase, I assume your application looks different, but I think you got some direction from this snippet.

I would hide the token to an environment variable.

When you deploy your server to heroku you are going to get an url, and in your front-end you can replace the url easily and deploy it.

like image 146
Sándor Bakos Avatar answered Oct 23 '25 19:10

Sándor Bakos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!