If you’re going to put it on Github, then you can use Github Pages with a private repository, but that doesn’t solve your problem, because every time this API is called, anyone can see the parameters (in this case, client_id
), simply inspect the requests by the browser itself.
To ensure that no one will see this key, the API call should be made by a backend server, not directly on the frontend. On Github Pages it is not possible to host a backend server.
In short, it should be like this:
- The frontend (in this case Github Pages) calls an API to a backend server;
- Your backend server calls the API to Unsplash;
- Unsplash answers some data to your server;
- Your server responds to frontend.
You can use free services (such as Heroku) to host your backend. I recommend using the Express framework with Axios.
Basically, your backend server would be:
var express = require('express');
var app = express();
var axios = require('axios');
app.get('/sua-rota', function(req, res) {
//chama a api do Unsplash
axios.get('https://api.unsplash.com/photos/random/?client_id=[minha-id]')
.then(function (response) {
res.send(responde.data);
})
.catch(function (error) {
res.status(500).send(error);
})
});
Now, in your Github project, instead of calling the Unsplash API, you should call your server API. If you stay at Heroku, it will be something like this: nome-do-site.herokuapp.com/sua-rota
You can use environment variables for this. Packages like
dotenv
may help, although they are not entirely necessary.– Luiz Felipe
Environment variables on Github Pages?
– Lauro Moraes
@Lauromoraes, what do you mean Github pages? AP hasn’t talked at any time about Github pages...
– Luiz Felipe
@Luizfelipe commented on the question "to put in my portfolio on github" and "so the pages of github tb not..." so I imagine be pages Estaticas not?
– Lauro Moraes
@Lauromoraes, really. There even complicates, I had not paid attention to this "detail". Another option would be to use some service like Vercel or Netlify to allow a custom "build" step for the static site, then the environment variable would become a viable option, still keeping the site static. Other than that, on Github pages even, really, you can’t use environment variable even if you don’t. :/
– Luiz Felipe
I would recommend doing a proxy with Cloudflare cloudworker or using Glitch.com ... but would need to study the documentation. So you could hide the key to the API
– Lauro Moraes
Hello M.F, put this key in a file like . env or . ini and that file should not be sent to git, so put env or ini in . gitignore to avoid going up and load this value called by your application into a variable that will replace the
[minha-id]
– Guilherme Nascimento