I have a problem, updated my app to newest nextjs (13.1.6), however all my request ar failing now. Somehow, the URL I set up in the request creator, based on the ENV value, is getting overwritten.
.env file
CONST NEXT_PUBLIC_API_URL = 'HTTPS://API.COM';
requestCreator file
const response = await fetch(process.env.NEXT_PUBLIC_API_URL);
Before updating, the requests were sent properly to URL:
https://api.com/some-path
But after nextjs update, the requests are being sent to:
http://localhost:3000/_next/data/development/en/some-path
Why does this happen? How to solve it?
To expose env to the browser his name should started with NEXT_PUBLIC_.
But this rule old enough. Maybe you used very old Next version
https://nextjs.org/docs/basic-features/environment-variables#exposing-environment-variables-to-the-browser
Related
I'm having a really strange interaction with my env file when trying to use it in a fetch request.
.env:
URL = http://localhost:3000/
fetch request:
fetch(`${process.env.URL}api/data`,{})
return:
http://localhost:3000/undefinedapi/data
I have also tried changing the fetch request to:
fetch(`${process.env.URL}/api/data`,{})
return:
http://localhost:3000/api/data
This slightly fixed the url structure but doesn't help the act that for some reason it's adding undefined after the proccessing the env.
If you are using react-scripts all custom variables requires a prefix REACT_APP to be exposed.
Every custom variable without prefix will return undefined.
Try change the URL to REACT_APP_URL and process.env.REACT_APP_URL
I've got a new API from the backend team in a new project, when I call the api it returns "you need to enable java...", whereas I had used Postman for another project before... is it related to api, server or something else?
I don't think that POSTMAN is capable of executing JavaScript in its console.
Try doing the same in the web browser it will work (You won't see this error message).
I spent some times pondering on this trepidation.. and then suddenly i realized what was going on..
the endpoint does not exist, it could be a misspelling
not in the same directory as you expect it to be,
try adding or removing "/" at the beginning of the url, particularly if you don't specify the hostname, i.e. fetch('getusername') is different from fetch('/getusername') .
. This acceptable in development but NOT when already deployed, it points to different path.
the endpoint may be working fine in the Development,
but somewhere within in the Production/Staging, it generated some exception.
I updated Postman and now it works. I'm not sure if it was because of the update or the restart.
I had this problem with a project built using the new template in Visual Studio 2022 for a React app with .NET Core.
In my case I was only getting the response "You need to enable JavaScript to run this app" with calls to a new controller I added. Calls to the built-in WeatherForecastController were working just fine. My new controller was configured the same as the built-in controller so I could not figure out why this was happening. It has to do with how this project template creates both a React app and a back-end API both accessible on the same port. There's a setupProxy.js file that defines routes that should be forwarded to the API. All other routes are redirected to index.html. This is actually what was happening in my case, because my new controller had not been added to setupProxy.js the middleware was redirecting the request to index.html, and because it came from Postman rather than a browser the message regarding enabling JavaScript is displayed.
The solution is that each controller must be explicitly mapped in setupProxy.js or else it won't be proxied correctly. After making this change it worked perfectly in Postman as well as fetch calls from the React app.
const context = [
"/weatherforecast", // built-in controller than comes with the project template in VS2022
"/recaptcha" // controller I created (this line must be added)
];
While calling the REST API with the postman, if you miss the end-point, then also this issue will come, add the end-point to the URL and check
What worked for me was to turn-off / deselect the user-agent header field under request
I have implemented a small localStorage with react, where I save URI endpoints once the users enters them, and I call them on my componentDidMount function if they exist.
The setup seemed super simple and it totally worked while I was doing npm start on my dev files, however on building my project and hosting it locally using 'serve', I am not able to see my localStorage anymore. Does this have to do something with the build files or the way I'm serving them?
componentDidMount() {
userUri = localStorage.getItem('userUri');
tracesUri = localStorage.getItem('tracesUri');
if (userUri && tracesUri) {
this.setState({
userUri: userUri,
tracesUri: tracesUri
});
}
};
closeModal = () => {
this.setState({
showSettings: false
});
localStorage.setItem('userUri', this.state.userUri);
localStorage.setItem('tracesUri', this.state.tracesUri);
};
If I understand your question correctly, when you run your app locally, you are not able to see the data that was persisted when you ran your app via npm?
Something to keep in mind is that data stored via localStorage is restricted to the current document.origin see MDN docs here.
You need to ensure that you are testing/running locally at the same origin for the same persisted data to be visible in both cases.
You can add this code to your app:
console.log('Origin is:', document.origin);
This will print the origin to console, and then cross check this origin by running the app both via 'npm' and by hosting locally to verify that the origin is the same or different
Access to data stored in the browser such as localStorage and IndexedDB are separated by origin. Each origin gets its own separate storage, and JavaScript in one origin cannot read from or write to the storage belonging to another origin.[ref: link]
So I guess while you serve, you must be using a different port due to which you were not able to access the previous localStorage values.
I'm setup my initial js file like so however on build I'm getting an error that the client now requires my client secret and client id .. What's weird is that when I first built my app all initial API requests went through with just the api key. I can see my uploaded + training pictures on the clarifai preview UI so I know they completed successfully. Every call since then has failed though. Not sure where I get the client secret and id since the documentation only provides me with an api key.
// Require the client
const config = require('../config/config');
const Clarifai = require('../../node_modules/clarifai/src');
// initialize with your api key. This will also work in your browser via http://browserify.org/
const app = new Clarifai.App({
apiKey: config['CLARAFAI_API_KEY']
});
As stated on the website...
After creating your API Key, you are ready to make API calls. If you are using a client, authentication will be handled for you. If you are using the REST API, you will need to add the Authorization header as described in the cURL example.
EDIT 7/27/2017:
Screenshot of error msg
As you can see on their authentication post. They have deprecated the client/id and secret and remove them from Nov 15, 2017.
I think you should update your js package.
It will just work fine.
I'm building my first Express app, which needs to interact with an API, using an API key that ideally remains secure.
So I wanted to follow a basic pattern of keeping the key (and any future environment variables), in a .gitignored .env file in the root directory.
To not reinvent the wheel, I used this package, and set my env variables like so, in my app.coffee file (the root file of the application):
env = require('node-env-file')
env __dirname + '/.env'
console.log process.env.MY_API_KEY
That console.log prints out the right key to the server logs. The problem arises later:
If I try to access that same variable in one of the JS files loaded later on by my app, process.env is an empty object, so the API key is undefined. This doesn't appear to be a problem with the above package, because if I define the variable in the CL (API_KEY=whatever npm start), the behavior is the same -- it console logs correctly from app.coffee but is unavailable later.
Some information on how the files in which the key is unavailable are being loaded:
The app is running React, which I write to a few .jsx files in public/javascripts/src, and which are compiled by gulp into public/javascripts/build/*.js.
I'm trying to access the key in a .js file in public/javascripts/ which is required by one of the .jsx files.
In that required .js file, process.env returns an empty object. When I try to access process.env in the .jsx files, I'm actually told that process itself is undefined.
Any ideas what's going on here? I'm new to Express/React, and unclear where this process object, which I thought was global and defined on npm start is defined, and what's happening to all the env info in it.
Thanks! Please let me know if any other information would be helpful, orif anyone has any suggestions for how better to handle private env info in my situation.
EDIT:
I tried the suggestions below, and created a separate endpoint internally, which hits the external API and then returns a response. I've strung things up correctly, so that this responds correctly:
router.get '/images', (req, res, next) ->
res.json({ some: 'json' });
but this (which uses a separate class to make a request to an external API), throws an error:
router.get '/images', (req, res, next) ->
new Images('nature').fetch (images) ->
res.json({ some: 'json' })
Essentially, it looks like the asynchrony of the response from the external API (and not even the data itself, which I ignored), is creating a problem. How do I hit this external endpoint and then respond to the internal request with the incoming data?
Back-end vs Front-end
It seems like you are trying to access back-end data from a front-end location, in a wrong way.
The great power of Node.js is having JavaScript in the front and in the back, but it is quite confusing in the beginning to understand on which side each script is executed.
In an Express project, all Javascript files that are sent to the front-end, those that will directly interact with the client's page, are located in public/javascripts/. Generally you will have some AJAX functions in some of those files to exchange data and communicate with the back-end.
These back-end files are located everywhere else : in the root directory, in routes/, and all the other folders you create. Those files are pretty much all connected to your Node instance, and therefore can communicate with each other using global objects like process for example.
Your script in public/javascripts/, that is executed on the client's computer, is trying to directly access a variable located on the server running your Node instance : that's why your code doesn't work. If you wish to access data from the back-end, you must use AJAX calls in the front-end.
Server <---(AJAX only)--- Client
------ ------
app.js public/javascripts/script.js
routes.js
...
That being said, you wanted to keep your API key private, which will not happen if you send it to every client who's on that specific page. What you should do is make the call from the back-end, using the xhr module for example, and then delivering the data to front-end, without the secret API key.
I hope I was clear, Node is quite confusing at first but very soon you will get over these little mistakes !
All .jsx is, is some code, what matters is where the code is being executed. process.env is a variable that is accessible inside the Node.js runtime. When your .jsx code gets transpiled down to .js and served to the browser, the process.env variable will no longer exist. If you're making an API call inside the browser, the API key will be fundamentally available to the client. If you want to secure the key, you have to have your Node.js server expose an API route, which your React app will hit. That Node.js server will then make the call to the external service using the API key. Because that call is being made by the server, process.env will be available, and will remain hidden from the client. You can then forward the result of the API call back to the user.