I am working in graphql using node js. I want to get the hostname of a server and use it in anywhere of file.
here is my code:
app.use('/api',graphqlHTTP((req,res)=>({
context:{
oauth_token:req.oauth_token,
host : req.headers['host'],
ip: req.ip
},
schema,
graphiql: true,
})));
I am accessing it in schema file through resolver. Like:
resolve: (parent, args, context, resolveInfo) => {
host = context.host;
}
Here I can fetch hostname. But how could I use it in any file?
If the hostname is a static value and is something you have control of I would suggest to use the node environmental variables. There are 2 common ways to use it: 1. command line 2. .env file
1) Simply indicate the name of the variable following by equal sign and then the value itself. After that start your node server
HOST=localhost node server.js
And then you can use it in your app like so:
// server.js
const host = process.env.HOST;
2) Create a .env file in the root of your app and set the variables there:
HOST=localhost
PORT=8080
API_KEY=123123
I would personally prefer the second one as you just set it up once and no need to type it in the console every time you start the server. Just don't forget to include it in your .gitignore
as your history will have references to your secrets then