onmyway133 / blog

🍁 What you don't know is what you haven't learned
https://onmyway133.com/
MIT License
679 stars 33 forks source link

How to serve a local development environment over https using pnpm and webpack #976

Open onmyway133 opened 3 months ago

onmyway133 commented 3 months ago

When developing locally, especially when interacting with third-party services that have CORS restrictions, serving your development environment over a custom domain with HTTPS can be crucial. Let’s walk through the steps to achieve this with pnpm and webpack. In our example, the domain we want to use is local.onmyway133.com

Map Localhost to Your Domain Name

First, we need to map our custom domain to localhost. Open your hosts file to add this mapping.

sudo vim /etc/hosts

Add the following line to the bottom of the file:

127.0.0.1  local.onmyway133.com

Save the file :wq and close your editor.

Generate a Self-Signed SSL Certificate

Next, we’ll generate a self-signed SSL certificate. Run the following command from the root of your project directory:

mkdir ssl
openssl req -x509 -out ssl/local.onmyway133.com.crt -keyout ssl/local.onmyway133.com.key -newkey rsa:2048 -nodes -sha256

You’ll be prompted to answer several questions. For the Common Name, enter local.onmyway133.com.

After completing the process, you’ll find the .crt and .key files in ssl folder

Trust the SSL Certificate

Double-click the generated .crt file to add it to Keychain Access. Once added, set the certificate to Always Trust.

image

Configure webpack dev server for HTTPS

Now, we need to configure webpack-dev-server to use our custom domain and HTTPS. Update your webpack.config.js with the following:

module.exports = {
  // other webpack configurations...
  devServer: {
    host: "local.onmyway133.com",
    port: 80,
    server: {
      type: "https",
      options: {
        key: "/users/khoa/downloads/ssl/local.onmyway133.com.key",
        cert: "/users/khoa/downloads/ssl/local.onmyway133.com.crt",
      },
    },
  },
};

Now, you’re ready to start your development server. Run the following command in your terminal:

pnpm start // webpack serve

Your application should now be accessible at https://local.onmyway133.com.

By following these steps, you’ve set up your local development environment to serve over a custom domain with HTTPS, allowing you to interact with third-party services that have strict CORS policies. This setup ensures a smoother and more secure development experience.

For more details on webpack-dev-server configuration, refer to the webpack documentation.