Next js app server setup with AWS

setup AWS server for next js website with Cloudflare domain

Step 1-

login to your AWS server in your local terminal or in Termius (I’m using here).

Termius login-
- add title
- add the IP address
- add username
- add password / pem file

Step 2-
install node js and Nginx, (if already exists then avoid this step)

// install node js latest version (16)
$curl -sL https://deb.nodesource.com/setup_16.x -o nodesource_setup.sh
$sudo bash nodesource_setup.sh
$sudo apt install nodejs
// install Nginx
$sudo apt update && sudo apt install nginx -y
$sudo ufw allow 'Nginx HTTP'
$sudo service nginx start

You check this document for SPA (click)

Step 3-
Now it’s time to configure your domain to nginx

open nginx default configuration file
first navigate to /etc/nginx/sites-available

and open default file with nano editor — and add the below

server {
listen 80;
listen [::]:80;
#listen 443 ssl;
server_name staging.website.com;
#ssl_certificate /etc/ssl/myApp/website_com.crt;
#ssl_certificate_key /etc/ssl/myApp/server.key;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}

save this file and restart Nginx sudo service nginx restart

Add SSL certificate for HTTPS & default redirect to HTTPS

server {
listen [::]:443 ssl;
listen 443 ssl;
server_name staging.website.com;
ssl_certificate /etc/ssl/myApp/website_com.crt;
ssl_certificate_key /etc/ssl/myApp/server.key;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
server {
if ($host = staging.website.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80 ;
listen [::]:80 ;
server_name staging.website.com;
return 404; # managed by Certbot
}

Now you can run your app on your domain with HTTPS. https://staging.website.com/

Note: but it will show 502 status code as no app is running on port 3000 on our server. so we need to run our application on our server

checkout to the directory cd /var/www/html

clone your website repository here from the git platform (Github | bitbucket …etc)

checkout to your repo — cd <my_repo>

install all packages and run build

$npm install
$npm run build

Note: make sure that your app is running on a related port defined in the Nginx configuration

run your application with forever or pm2

with forever — forever start server.js

with pm2 — pm2 start server.js --name "app_name"

Now it’s time for circle ci configuration

— — — — — — — — — — — — — — — — — — — —

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store