DEV Community

Cover image for How to Securely Host Frontend and Backend Together
Arunangshu Das
Arunangshu Das

Posted on

How to Securely Host Frontend and Backend Together

Let’s be honest—building a great app isn’t enough. You could write elegant code, perfect your UI/UX, and optimize your APIs to the core, but if your deployment is messy or insecure, everything else could crumble like a house of cards.

Whether you're a solo developer launching your dream SaaS product, a freelancer managing multiple client websites, or a team scaling a production-grade app, knowing how to host frontend and backend together securely is a superpower. But the problem is—there’s too much noise. Too many platforms, deployment workflows, certificates, reverse proxies, and most importantly, too many ways to mess it up.

So, how do you simplify this chaos without compromising on security or scalability?

Why Host Frontend and Backend Together?

Before jumping into the “how,” let’s answer the “why.” Is it even a good idea?

Yes, and here’s why it can be awesome:

  • Improved DevOps Simplicity: One deployment pipeline, one server or platform, one place to debug.
  • Performance: When frontend and backend are hosted together, they can share the same domain. This reduces DNS lookups and improves latency.
  • Security: Fewer exposed endpoints across different domains reduces your surface area for attack. Shared security policies become easier to manage.
  • SEO & SSR: If you’re using SSR frameworks like Next.js or Nuxt, keeping things together is not just convenient—it’s essential.
  • Session and Cookie Handling: Avoid CORS and cross-domain cookie issues.

But none of this matters if you don’t secure the stack.

A Real-World Stack We’ll Use in This Guide

Let’s assume a very common real-world setup:

  • Frontend: React (built using Vite or Create React App)
  • Backend: Node.js/Express or Fastify (REST or GraphQL)
  • Hosting Platform: A secure cloud platform (Cloudways or similar)
  • Server: Ubuntu-based VPS or containerized environment
  • SSL: Let’s Encrypt or custom SSL
  • Domain: Single domain (e.g., myapp.com) or subdomains (e.g., api.myapp.com, app.myapp.com)

And yes, if you’re not a full-time DevOps engineer, this might feel overwhelming. That’s why we’ll show how you can do this on platforms like Cloudways, which take care of most of the heavy lifting, while still giving you root-level control.

Step-by-Step: Securely Hosting Frontend + Backend

Step 1: Build Your Frontend (Static Files)

Most modern frontend frameworks (React, Vue, Svelte) compile down to static assets.

npm run build
Enter fullscreen mode Exit fullscreen mode

This will generate a dist or build folder containing index.html, JavaScript bundles, and assets. These files can be served using any static file server.

Best Practice:

  • Minify and compress your output.
  • Use hashing in filenames for cache busting.

Step 2: Setup a Secure Backend Server

Create a Node.js server that serves your API and optionally your frontend.

const express = require('express');
const path = require('path');
const app = express();
 
// Security headers
const helmet = require('helmet');
app.use(helmet());
 
// Rate limiting
const rateLimit = require('express-rate-limit');
app.use(rateLimit({ windowMs: 15 * 60 * 1000, max: 100 }));
 
// CORS (if frontend is on different domain)
const cors = require('cors');
app.use(cors());
 
// Serve static files
app.use(express.static(path.join(__dirname, 'build')));
 
// API routes
app.use('/api', require('./api'));
 
// Fallback to index.html for SPA
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
 
app.listen(3000, () => console.log('Server running securely on port 3000'));
Enter fullscreen mode Exit fullscreen mode

Security Checklist:

  • Use helmet for HTTP headers
  • Enforce HTTPS (either via proxy or SSL)
  • Set proper CORS policies
  • Add rate limiting
  • Validate and sanitize inputs

Step 3: Pick a Hosting Platform That Doesn’t Make You Cry

This is where developers often get stuck.

Some go full DIY with a VPS (like DigitalOcean or AWS EC2), but end up spending hours configuring NGINX, setting up firewall rules, worrying about updates and patches.

If you want a developer-friendly yet scalable hosting experience, Cloudways is an excellent choice.

You get:

  • 1-Click deployment for Node.js apps
  • Easy SSL installation
  • Integrated firewalls
  • Server monitoring
  • Application-level isolation
  • Git + CI/CD support

It’s basically a managed hosting platform without vendor lock-in. You still choose your infrastructure (DigitalOcean, AWS, etc.), but Cloudways handles security, updates, and performance tuning. It saves hours—especially if you’re running a startup or side project with limited DevOps bandwidth.

And let’s be real—what you save in DevOps cost easily offsets the subscription.

Step 4: Set Up Your Server Environment (with Cloudways or VPS)

Once you've chosen your platform, here's what to do:

  1. Provision a Server
  • Choose your cloud provider and server size.
  • Select a data center near your audience.
  1. Install Node.js App
  • Use a Node.js template on Cloudways.
  • Or manually install using pm2 on a raw VPS.
  1. Deploy Your Code
  • Use Git, SFTP, or CI/CD tools.
  • Set your environment variables.
  1. Enable HTTPS
  • Install Let’s Encrypt SSL via Cloudways UI (2 clicks).
  • For VPS, use Certbot:

 

  sudo apt install certbot
  sudo certbot --nginx
Enter fullscreen mode Exit fullscreen mode
  1. Configure Firewall
  • Only allow essential ports (80, 443, 22).
  • Use Cloudways’ security group settings.

Step 5: Use Reverse Proxy or Serve Frontend from Backend

There are two ways to connect frontend + backend:

Option 1: Serve Frontend Through Backend

This is the easiest method. Your Express app will serve static files, as shown earlier. Works great for SPAs.

  • One domain (myapp.com)
  • No CORS issues
  • Easier SSL setup
  • Backend must also restart if frontend changes

Option 2: Use Reverse Proxy (NGINX)

Here, you deploy frontend and backend as separate services and use NGINX to route.

Example:

server {
    listen 80;
    server_name myapp.com;
 
    location / {
        proxy_pass http://localhost:3001;  # React app
    }
 
    location /api {
        proxy_pass http://localhost:3000;  # Node API
    }
}
Enter fullscreen mode Exit fullscreen mode
  • Independent deployments
  • Better scaling
  • CORS and subdomain config needed
  • Slightly more complex

If you're on Cloudways, reverse proxy rules can be configured using their UI or by editing server config via SSH.

Essential Security Enhancements

You’ve hosted the app. Now let’s harden it.

1. HTTPS Everywhere

If users can still access HTTP, you’re vulnerable to MITM attacks.

  • Use Cloudways' free SSL + auto-renew.
  • Redirect all traffic to HTTPS in your server code or NGINX.

2. CSP Headers

Use Content Security Policy to restrict scripts/styles loading:

app.use(helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ["'self'"],
    scriptSrc: ["'self'", "trusted-cdn.com"],
    styleSrc: ["'self'", "fonts.googleapis.com"],
  }
}));
Enter fullscreen mode Exit fullscreen mode

3. DDOS Protection

Most managed platforms like Cloudways include basic DDOS protection. For VPS, you can use:

  • Cloudflare Proxy
  • Fail2ban
  • IPTables

4. Database Security

  • Never expose MongoDB/Postgres ports publicly.
  • Use SSH tunnels or internal networking.
  • Rotate credentials every 60–90 days.

5. Monitoring & Logging

Use a combination of:

  • Cloudways Application Monitoring
  • PM2 logs
  • Uptime Robot or Pingdom

Bonus: Simplified CI/CD for Full-Stack Apps

Automate your deployments with Git-based workflows:

  • Push code to GitHub
  • Webhook triggers build on your backend
  • Frontend rebuilds and deploys with post-hook script

On Cloudways, you can set deployment hooks, configure multiple Git branches, and auto-deploy to staging or production. This keeps you agile and secure.

Summary Checklist

Task                                        Done?
Built secure static frontend                ✅    
Created secure Express backend              ✅    
Served frontend via backend or NGINX        ✅    
Enabled HTTPS and firewall                  ✅    
Deployed to secure cloud platform           ✅    
Configured monitoring, rate limits, headers ✅    

Final Thoughts

You don’t need a huge DevOps team to securely host your full-stack app. What you do need is a good understanding of the moving parts—and a platform that simplifies complexity without compromising power.

Platforms like Cloudways are made exactly for developers like us—those who want full control when needed, but also want to sleep at night knowing SSL, updates, and security are handled. And that’s what makes all the difference.

So the next time you're launching your product, client project, or MVP—don’t overcomplicate your hosting.

Keep it simple. Keep it secure. And if you’re ready to deploy something that just works, try a managed platform that won’t slow you down.

You may also like:

  1. 5 Benefits of Using Worker Threads in Node.js

  2. 7 Best Practices for Sanitizing Input in Node.js

  3. 5 AI Developer Tools to Double Your Coding Speed

  4. 10 Essential Steps to Organize Node.js Projects on Cloudways

  5. What is GeoIP Rate-Limiting in Node.js on Cloudways?

  6. 6 Common Misconceptions About Node.js Event Loop

  7. Deploy a Node.js App on Cloudways in 10 Minutes

  8. 5 Reasons to Deep Copy Request Payloads in Node.js

  9. 5 Essential Tips for Managing Complex Objects in JavaScript

  10. 7 API Best Practices Every Backend Developer Should Follow

Read more blogs from Here

You can easily reach me with a quick call right from here.

Share your experiences in the comments, and let’s discuss how to tackle them!

Follow me on LinkedIn

Top comments (0)