1

It's simple, I have a very long api url 'https://namerandomlarge.api.com/'.

I would like to store it in a variable called MyApiUrl, so I can use it in my components and methods whenever I want.

What would be the right way to do it?

Antonio Morales
  • 1,044
  • 2
  • 16
  • 35

3 Answers3

3

I usually put things like that in a constants.js file in project folder.

export const API_BASE = "http://localhost:5000/api"

or as a .env variable if it is something I wouldn't want in git repo.

linusw
  • 1,140
  • 3
  • 9
1

Why don't you use .env file and access it through your application.

API_URL=https://namerandomlarge.api.com/
4b0
  • 21,981
  • 30
  • 95
  • 142
Paulo
  • 41
  • 3
0

You can create a .env file in your root directory of the project and then add the common URL's in that file.

MY_API_URL=https://namerandomlarge.api.com/

You can access this in your component script code like this :

process.env.MY_API_URL

One advantage of creating .env file is that you can use these files dynamically based on the environment. For example : In Dev, you want to execute some different URL's and in prod env, You have some different. In this case you can create two env files .env.dev and .env.prod and then call based on the environments you are running.

Debug Diva
  • 26,058
  • 13
  • 70
  • 123
  • I feel like this answer does not fully represent the usage of env variables. How to set up and use environment variables can differ according to the setup. For example, using vite, you can access env variables as [`import.meta.env`](https://vitejs.dev/guide/env-and-mode.html#env-files). – cSharp Jun 22 '22 at 04:51