Launch fast an HTTP server locally and test your application

· 3 min read
Launch fast an HTTP server locally and test your application

Τhere are innumerous occasions when we need to launch an HTTP server locally to test a Single Page Application, or a production bundle or even a static website.

Most major frontend frameworks offer a solution through webpack-dev-server for development purposes. But what happens when we need to build a production bundle locally, in order to test its behaviour, before shipping it to production environment?

This can be accomplished with a bunch of ways, sometimes even by using solutions outside of NodeJS ecosystem.

All examples below will serve our application on port http://localhost:3000 for consistency reasons.

# Using Python

With Python, we can simply call SimpleHTTPServer:

cd ./myProject

python -m SimpleHTTPServer 3000

# Using PHP

While with PHP, we can do:

cd ./myProject

php -S localhost:3000

# Using Ruby

With Ruby, all we need is:

cd ./myProject

ruby -run -e httpd -- -p 3000

These are just a few solutions of course with some well-known programming languages, but I am sure you got the picture that there are tons of quick ways to accomplish this.

# NodeJS solutions

When it comes about NodeJS solutions and npm packages we can use even more advanced options with many goodies such as live-reload, proxying, SSL usage and many more.

Let's see some of them a bit closer.

# Using serve

serve package is a pretty simple and robust HTTP server built with nodeJS. We can use it to serve our application with the bare minimum configuration amazingly fast:

npx serve ./myProject -l 3000

# Using lite-server

lite-server is an HTTP server built as a wrapper around BrowserSync so it offers livereload out of the box for better development experience.

It opens our application in the browser, refreshes when html or javascript change, injects CSS changes using sockets, and has a fallback page when a route is not found. Pretty neat!!

cd ./myProject

npx lite-server

If we need to override its default configuration options we can create a custom bs-config.json or bs-config.js file for our project:

{
  "port": 8000,
  "files": ["./src/**/*.{html,htm,css,js}"],
  "server": { "baseDir": "./myProject" }
}

Then, we can simply run:

lite-server -c bs-config.json

# Using http-server

Last but not least we can use http-server which is actually a powerhouse. We can launch it by running:

npx http-server ./myProject -p 3000

It offers a ton of goodies for even more advanced debugging like:

  • gzip compression
  • brotli compression
  • proxying
  • basic authentication
  • SSL usage for debugging under https even for localhost
  • and many more...

Pretty impressive I suppose, right? 🚀

Did you like this one?

I hope you really did...

Marios_thumb

Newsletter

Get notified about latest posts and updates once a week!!