How to bind a domain name to expressjs application - node.js

How to bind a domain name to expressjs application.My application is running on servername:1001
I want to bind it to www.domainname.com. How can I do this in the application.

I'm searching for the same answer.
I have just been using app.use('/', router) with a processor that then checks the domain off the req object.
router.get('*', (req, res, next) => {
let path = req.path.replace(/^\//g,'').replace(/\/$/g,'');
let domain = req.headers.host.split(':')[0];
domain = domain.replace(/^www\./g,'');
});
This is the closest thing I've been able to come with to actually using express routes per domain. On my own, 4 years ago.
Now there seems to be this VHOST module:
http://expressjs.com/en/resources/middleware/vhost.html
-Robert

Your DNS record you should use CNAME. As a value you should use the domain your hosting provider gave you ex. myapp.herokuapp.com(which on heroku side point to servername:1001).
If you are using hosting like heroku, you should setup to accept traffic for your application for that specific domain. That last configuration is being made on heroku management site.

Related

Nodejs : how to redirect subdomains to ports?

I'm creating a fullstack web-app with an API as backend, and I'm hosting it on a DigitalOcean server.
The front-end (reactjs) is running on a port (3000) and the backend (express server -RESTFul API-) on another (3001).
I would like to be able to communicate with both of them from a single domain.
Ex :
https://example.com/ => redirect to the front-end
https://example.com/a-specific-page => redirect to a specific page of the front-end
https://api.example.com/ => redirect to the backend API
https://api.example.com/login => redirect to the login part of the API
How can I do this ?
I've already tried some things :
redirect subdomain from my provider (ovh.com) => this is not the way
create a third nodejs server at the root on port 80 and redirect manually, but I don't think it's a good way because I have to consider all possibilities of domain name (www.mydomain.com / mydomain.com / http:/ etc...) and used concurrently to run all together
I don't really want to put frontend and backend in the same running server (same port)
I'm quite new in mastering servers so I don't kown nothing, sorry.
Thanks for the help.
PS: I'm french, so sorry for the bad English :)
Hello since i dont have that much information i will stay general.
What you want is a reverse proxy. You can use http-proxy-middleware: https://www.npmjs.com/package/http-proxy-middleware.
Let's say you run your frontend on http://example.com:3000 and your backend on http://example.com:3001.
Now lets say you want http://example.com:3001/42-is-the-answer to point to http://example.com:3000 (You can add a path if you want).
The only thing to do would be to use a proxy on the server instance of example.com:3001 like so:
const proxy = require("http-proxy-middleware");
const app = express();
....
app.use( proxy("/42-is-the-answer", {
target: "http://example.com:3000/"
}))
Now if you access http://example.com:3001/42-is-the-answer, the request will be proxied to http://example.com:3000.
I hope this helps.

Disable default domain https://[project-id].appspot.com of Node JS on Google App Engine

I have deployed my Node JS app onto Google Cloud App Engine, and I can successfully add my custom domain for my app.
Let say my custom domain is example.com.
Now I can browse my app via example.com & www.example.com, it works as expected. But I find that I can still browse my app through the default domain.
https://[project-id].appspot.com
I want to disable the default domain, is it possible to do that?
You cannot disable that default domain. You would have to write a redirect script. You can test for "appspot" in the request's HTTP_HOST, and test for "AppEngine-Google" in the request's HTTP_USER_AGENT, to determine if it is an internal request.
Also, internal functions, like cron jobs and task queues, run on that domain, so be careful what you do. Task queues will fail given a 301.
After considering GAEfan suggestion, I have made some change on the router logic. If the host name is ended with "appspot.com" and the user agent is included "AppEngine-Google", it will redirect to my custom domain.
router.get('/', function(req, res, next) {
if(req.get("host").endsWith(GOOGLE_APP_SPOT) &&
req.get("User-Agent").includes(GOOGLE_USER_AGENT))
{
var redirectURL = url.format({
protocol: req.protocol,
host: CUSTOM_DOMAIN,
pathname: req.originalUrl
});
res.redirect(redirectURL);
}
res.render('templateName', viewModel);
});
You can do it just using the dispatch.yaml file from App Engine, list all your domains there, but not the *.appspot.com one. Google will show a 404 route when you try to access that.
EDIT: Not possible anymore, check comments.
Checkout the official reference.

Running Keystone.js app over https on Heroku

I have a web app built on Keystone.js CMS for node.js that I will be deploying with a custom domain on Heroku. I want the whole app to run on https by default and not allow any http connections. I've look around quite a bit and can't seem to find a definitive answer as to the best way to go about this. Typically, i.e. for a Rails app, I would just buy a Heroku add-on SSL certificate for my custom domain(s) and point my DNS to point to the Heroku provisioned SSL endpoint. In my app, I would configure to default all connections to HTTPS.
For a node instance (and specifically a Keystone.js instance), I'm a little unclear. Can I just go about the same process as above, buy an SSL add-on and point my DNS to the Heroku SSL endpoint? Do I need to do anything in the base node code to support? And how to enforce https and not allow http?
New to node and keystone and so any help would be greatly appreciated!
Use express-sslify.
I put it in my routes/index.js since the function I export from there receives a reference to the express application.
All you need to do is to tell express to use sslify, but you probably want to not enable it for development.
Since july, Heroku defaults NODE_ENV to production so you can do
// Setup Route Bindings
exports = module.exports = function(app) {
if (process.env.NODE_ENV === 'production') {
var enforce = require('express-sslify');
app.use(enforce.HTTPS({ trustProtoHeader: true }));
}
// Declare your views
};
That will send a 301 to anyone trying to access your app over plain HTTP.

Generating subdomains on the fly

I am working on a MEAN application which provides people with their own unique sub-domain as part of their sign-up process. How to I do this?
I am open minded regarding what cloud services I use, I am impressed by Digital Ocean for example but it could equally be AWS. So long as it is scalable.
So how can you generate bobsmith.nicksamazingnewapp.com for example when Bob signs up with us? and for him to be able to use it right-away?
Virtual hosts are the way to go. Have a look at this new librabry for express I came across the other day. You are simply using the vhost middleware. https://github.com/expressjs/vhost
Here is a code sample from their site
// create main app
var app = connect()
// add vhost routing to main app for mail
app.use(vhost('mail.example.com', mailapp))
// route static assets for "assets-*" subdomain to get
// around max host connections limit on browsers
app.use(vhost('assets-*.example.com', staticapp))
fyi, if you are using mean.io then you need to add your middlware in the config/express.js file
I think the best solution would be to have a wildcard for subdomains so anything*.nicksamazingnewapp.com would be traped and then a server side you can decide to where it will point
app.get('/', function(req, res) {
var hostname = req.headers.host.split(":")[0];
if(hostname == "sub1.domain.com")
res.send("this is sub1 response!");
else if(hostname == "sub2.domain.com")
res.send("this is sub2 response!");
});
credits for code goes to #Jazor
you can also try a module https://www.npmjs.org/package/subdomain

how to develop a node.js app which supports multitenancies

I have a requirement that I want to serve multiple sites(host names) with the same port number.
These sites share the same code files, while only differ in that they have different site configurations and file upload folders.
basically it's just a cms which can host various domains, and usually each domain will have its own themes and configurations and of course db connections.
is there anybody who can give me some directions on this? Thanks very
much.
var subdomains = require('express-subdomains')
, express = require('express')
, app = Express.createServer()
// example: api.example.com/user -> '/api/user'
subdomains
.use('api')
.use('other.vanity.domain')
app.use(subdomains.middleware)
app.get('/api/user' function (req, res, next) {
// ..
})
app.listen()
https://github.com/tblobaum/express-subdomains
Each site should have it's own process and port, and you should proxy requests depending on the hostname.
You can use node-http-proxy or bouncy for proxy each site to its specific port. Another option is to use Express's vhost feature: https://github.com/visionmedia/express/blob/master/examples/vhost/app.js
You can easily support multiple domains from a single HTTP server codebase (see virtual hosting), you will just need to implement logic in your handlers to inspect the request host (e.g. in the Host HTTP header) and act conditionally based on its value. Then you can have any number of DNS names point to your server and act differently on them.
Here's an example:
http.createServer(function (request, response) {
var host = request.headers['Host'];
if (host == 'domain1.com') {
// Execute logic based on that host.
} else if (host == 'domain2.com') {
// Execute other logic...
}
}).listen(8080);

Resources