Horje
How to Hide API Key in JavaScript?

The Process of Hiding API keys in JavaScript is crucial for securing our application and preventing unauthorized access. API Keys should not be exposed in client-side code because anyone can view the source code and misuse the keys. The primary goal is not accessible to end users.

Prerequisites

Using Environment Variables

Using environment variables involves storing sensitive information like API keys on the server side rather than in the client-side code. This approach ensures the API key remains hidden and secure. The server-side application accesses the API key via environment variables and uses it to make requests to third-party services. The front end then interacts with the server-side application through an API endpoint, which handles the communication with the third-party service using the secured API key. This method prevents exposure of the API key to the client, enhancing security.

Example: Create dotenv and save the API key Information in that.

.env File

API_KEY=GFG$ARTICLES@#1234

server.js

require('dotenv').config();
const express = require('express');
const axios = require('axios');
const app = express();
const PORT = 3000;

// Load the API key from environment variables
const API_KEY = process.env.API_KEY;

app.get('/api/data', async (req, res) => {
try {
const response = await axios.get(`https://thirdpartyapi.com/data?key=${API_KEY}`);
res.json(response.data);
} catch (error) {
res.status(500).send('Error fetching data');
}
});

app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});




Reffered: https://www.geeksforgeeks.org


JavaScript

Related
How to Add event listener to Button in JavaScript ? How to Add event listener to Button in JavaScript ?
JavaScript SyntaxError – Unexpected template string JavaScript SyntaxError – Unexpected template string
Filter or map nodelists in JavaScript Filter or map nodelists in JavaScript
Split JavaScript Array in Chunks Using Lodash? Split JavaScript Array in Chunks Using Lodash?
How to Find Property by Name in a Deep Object Using Lodash? How to Find Property by Name in a Deep Object Using Lodash?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
21