What is the best way to incorporate an environmental variable in my AngularJS controller?

My API Key is securely stored in my '.env' file to keep it hidden from Git.

Here's a snippet of my .env file:

API_TOKEN=secrettokengibberish

When working on my Angular controller, I need to retrieve this variable for my AJAX call.

This is what the code looks like in StoryController.js:

var apiEndpoint = 'https://someapi.com/'+ $scope.myQuery +'.json?access_token=' + process.env.API_TOKEN;

However, I keep encountering an error message saying: 'process is not defined at StoryController'

Please note that I am still quite new to Angular and unsure if I am handling API keys correctly. Any guidance would be greatly appreciated.

Answer №1

It seems like you are attempting to set up a basic communication flow between Frontend, Backend, and an API:

+----------+         +---------+
|          | ---1--> |         |
| Frontend | <--2--- | Backend |
|          |         |         |
+----------+         +---------+
    |   A
    |   |           +-----+
    |   |           |     |
    |   \----4------| API |
    \----3--------->|     |
                    +-----+

However, for better security practices, it is recommended to structure your communication flow like this:

+----------+         +---------+         +-----+
|          | ---1--> |         | ---2--> |     |
| Frontend | <--4--- | Backend | <--3--- | API |
|          |         |         |         |     |
+----------+         +---------+         +-----+
                

It is not advisable to expose your token in the frontend. Instead, consider creating an endpoint in your backend to access the API securely.


Edit:

To achieve this, you can create an endpoint in your NodeJS backend using a framework like express:

var http = require('http');
var express = require('express');
var app = express();

app.get('/:myQuery', function (req, res) {
    var apiEndpoint = 'https://someapi.com/'+ req.params.myQuery +'.json?access_token=' + process.env.API_TOKEN;
    http.get(apiEndpoint, function(apiResponse) {
        apiResponse.setEncoding('utf8');
        res.status(apiResponse.statusCode);
        apiResponse.on('data', function (chunk) {
           console.log('BODY: ' + chunk);
           res.json(JSON.parse(chunk));
        });
    });
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

In your frontend Angular controller, you would make a request to this endpoint like so:

$http.get('http://localhost:3000/' + $scope.myQuery).then(function(){
   //...
});

Answer №2

To properly secure your application, it is recommended to implement authentication in Angular on the client-side.

Usually, users would log in through the front-end interface, and upon successful authentication, the back-end would send back the user credentials, token, and secret key to be used for subsequent requests. Storing any tokens directly within the front-end code poses a security risk as they could potentially be accessed by unauthorized users.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to transfer AJAX data to PHP script

Trying to figure out how to send AJAX data to PHP. While I am comfortable with PHP, JavaScript is a bit new to me. Incorporating HTML / JavaScript <input type="text" id="commodity_code"><button id="button"> = </button> <script id="s ...

Interact with CakePHP using onKeyUp event

Hey there, I have a quick and easy question. I'm working with a textbox that needs to trigger a javascript/jquery function whenever it is typed into. <?= $this->Form->input('contract_prices.'.$num.'.quantity', [ 'id ...

Encountering a compilation error when attempting to import a shader from a file in a project using THREE.js, Vue.js

I've encountered an error and spent hours searching for a solution, but unfortunately found nothing. The correct way to import shader code from a file is: import {ColourShader} from '../shaders/ColourShader.js' Here is the content of my &a ...

Is it feasible to access reference images contained within a zip/tar file using html/javascript with the help of a library?

Although this question may appear similar to others, there is a key distinction that sets it apart. In search of request efficiency rather than space efficiency, lazy loading could be the solution. However, in situations where content needs to be quickly ...

"Enhance your web application with dynamic drop-down selection using Spring, Ajax

In my JSP file, I have a script that populates the list of states based on the selected country. The script fetches data from the controller and is supposed to display the list of states. However, after calling the controller method, the alert "received da ...

Oops! Looks like there's an issue with reading the property 'value' of undefined in React-typeahead

Having some issues with setting the state for user selection in a dropdown menu using the react-bootstrap-typeahead component. Any guidance or resources on this topic would be highly appreciated. Details can be found here. The function handleAddTask is su ...

Injecting $scope and constants into an abstract state controller using ui router is not supported

I am currently utilizing angular 1.3.11 with the latest ui router version. Whenever I inject $scope or constants into my DateplannerController like so: 'use strict'; angular.module('test').controller('DateplannerController', ...

The use of `preventDefault()` in React for the `onCopy` event is ineffective

I'm currently exploring ways to prevent the clipboard events from copying text when the onCopy event is triggered. I've tried using the onCopy handler and e.preventDefault() method, but the text is still being copied without any issues. What am I ...

Submitting JSON data from React to a C# WebApi

I am facing an issue with my C# WebAPI action. I am attempting to send a JSON string to it using React. However, when I set the content type as application/json, I receive a 405 Method Not Allowed error. Sending the data as urlencoded works and gets into ...

What is the process for transforming an AJAX request's onreadystatechange into a promise?

During the process of making a javascript AJAX request, I initially utilized the traditional callback approach to call the callback function within the onreadystatechange and retrieve all the values of readyState. However, upon switching my callback funct ...

Ascending to the Peak within a div

<script type="text/javascript"> $(document).ready(function(){ updateContent(); }); function updateContent(){ $('#mainDiv').load('home.php', function(){ scrollToTop(); }); } ...

Transforming unknown JSON data into a fresh JSON structure

An undefined JSON object is being returned to a Node.js/Express.js application from a URL API endpoint http://someserver:someport/some_api_url?_var1=1. This particular JSON input always follows the same format and must be transformed into a new JSON object ...

Is SWR failing to provide outdated data?

My understanding was that SWR should display the cached data upon page load before refreshing with new information from the API. However, in my Next.js app with a simple API timeout, the "loading" message appears every time due to the 5-second delay I adde ...

Transform the column's datetime into a date in the where condition when using sequelize

Hey there, I'm looking to convert a datetime column into just date format while running a query. Could someone assist me with creating a Sequelize query based on the example below? select * from ev_events where DATE(event_date) <= '2016-10- ...

Submitting values using the serialize method and Ajax involves sending placeholders

Looking for a solution: <form class="pure-form pure-form-stacked" method="post" enctype="multipart/form-data"> <input type="text" name="name" class="button-size-1" placeholder="*Name"> <input type="text" name="email" class="but ...

Setting up popover functionality in TypeScript with Bootstrap 4

Seeking assistance with initializing popovers using TypeScript. I am attempting to initialize each element with the data-toggle="popover" attribute found on the page using querySelectorAll(). Here is an example of what I have tried so far: export class P ...

Using SQL in combination with FIND_IN_SET for efficient data filtering

My website's main page features a list of establishments that can be filtered by location, name, and services provided. The SQL table contains a numeric definition of these services for each establishment: id | name | location | services 1 ...

Exploring the world of cookie security with SameSite and Secure features in ExpressJS

Despite having the specified settings on my express application, a warning keeps appearing in the console. Has anyone encountered this error before? I found some information related to it here: https://github.com/expressjs/express/issues/3095 The version ...

PHP function not being called when Ajax request is made (PHP file not found)

I need assistance with a web page feature that allows the user to choose a team, triggering a change in an image.src to reflect the new selection. The chosen teamID is then saved in a settings file. However, I am facing issues with getting the AJAX call to ...

Can someone help me figure out the issue with my Angularjs ng-repeat implementation?

After spending hours trying to figure out why something so simple is not working, I'm at a loss. Testing with a dummy list proves the functionality works, but when I connect my server-side data source, it fails. The JSON returned from the AJAX call i ...