简体   繁体   中英

How to hide my api key which is normally embedded in a javascript file?

I am building a small website using LiveScore api from rapidapi.com. How can I hide my api key when deploying my application. Tried.env method, serverless methods but didn't do much help. I am trying the api hiding method for the first time. Maybe that's why I am not getting it. Is there any method to hide api key which is fairly simple but a decent hiding?

//index.js

const options = {
method: 'GET',
headers: {
    'X-RapidAPI-Key': 'xxxxxxxxxx',
    'X-RapidAPI-Host': 'livescore6.p.rapidapi.com'
}
};

fetch('https://livescore6.p.rapidapi.com/matches/v2/list-by-date?   
Category=soccer&Date=20231801&Timezone=-7', options) 
.then(
response => {
    response.json().then(
        data => {
//my code here
})

In plain client side Javascript there is not much you can do to hide API Keys. I took a quick glance at the RapidAPI docs and also this blog post from them, but they just use the API Keys as-is without securing anything. (lol)

So if you're worried about that information leaking, I would recommend you to create a backend in any backend language you prefer (it could be NodeJS, if you want to use Javascript) and use it as a proxy to make a request to that LiveScore API. If you do this you don't have to hardcode the API Keys in your client code, you could use dotenv in your backend, also you could control which endpoints to use and even add some custom basic authentication to be able to make a request.

This is a basic example using NodeJS and express :

const express = require('express');
const fetch = require('node-fetch');
const cors = require('cors');
const app = express();

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

app.get('/api/livescore', async (req, res) => {
  try {
    const options = {
      method: 'GET',
      headers: {
        'X-RapidAPI-Key': process.env.RAPID_API_KEY,
        'X-RapidAPI-Host': process.env.RAPID_API_HOST
      }
    };

    const rapidApiResponse = await fetch('https://some-rapid-api-endpoint.com', options);

    const parsedResponse = await rapidApiResponse.json();

    return res.json({ data: parsedResponse });
  } catch (err) {
    return res.status(500).json({ err: err.message });
  }
});

app.listen(process.env.PORT || 3000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM