- [Instructor] Usually we don't want Node.js
to directly serve a website.
Things like SSL or TLS encryption
are doable, but a web server
was exactly made for such a task.
That's why the most common setup
is running Express Apps behind
some reverse proxy like Nginx.
On my EC2 instance, I've already installed Engine X
and I used Let's Encrypt to install
and setup a free SSL certificate.
I've also already took care of the proxy configuration.
Let's look into it real quick.
So I'm going into /etc/nginx/sites-enabled/default,
and there now see this section with location /.
So the most important part is the proxy_pass directive here.
This tells Nginx to reverse proxy everything
to localhost on port 3000.
For complete overview of all the proxy directives,
please refer to the Nginx documentation.
To let Express run behind the proxy properly,
we also have to make a few adoptions to the code.
So I had backed individual studio code,
and in app.js I will now make a few adjustments.
First of all I want to distinguish
if we're running in development or in production.
So now add run line 43,
if(app.get('env')), this gives us
the current environment we're running on equals production,
and I want to do a few things differently.
I'm doing the else branch, and there I copy in,
for instance, the setup of the session.
So we're running production means behind a proxy,
and Express as an option that tells
it that it's running behind a proxy.
If you don't set that, it might happen
that the IP address of the users is not reported correctly.
So we are setting trust proxy
and we trust here the loopback device,
which is our localhost.
And additionally we also want to change
the session handling a little bit,
so I'm copy over the setup of the session
from the else block.
And there, for instance, I want to change
the secret, and additionally,
I also want to change the session Id name,
because if we leave the default, which is connect.sId,
someone might be able to infer
that this is an Express server,
and the less we expose about ourselves, the better.
Next we also want to configure
that we are running behind a proxy.
This makes a few more adjustments
to how the session management works,
and additionally as we're now behind a SSL connection,
we can force the browser to only send secure cookies.
Now let's commit it to my version control,
updated for proxies, and let's upload from here.
Push to the server.
And now we can simply use pm2 update
to push our current application,
and now we can simply use pm2 deploy production
to push all those changes to the server.
Let's head over to the browser now,
and let's open https and the URL
where the website is running on,
and we see that it's now served via https.
Now let's make a quick test.
Let's register new user.
And password, and we want to upload a picture.
Let's submit, and let's login with this user,
and we see that it works as suspected.
We now have a working website served
via https and running on the internet.