How can I provide a SSL certificate with create-react-app?

后端 未结 6 1409
南方客
南方客 2020-12-04 16:32


I am trying to host a react app I created and tested locally using the facebook boilerplate.
The client app interacts with an API I made using node.js, and with

6条回答
  •  青春惊慌失措
    2020-12-04 17:27

    Update: see Andi's answer below. In recent version you should set environment variable to configure the certificate

    SSL_CRT_FILE=.cert/server.crt
    SSL_KEY_FILE=.cert/server.key
    

    Ejecting create-react-app is not recommended since you won't be able to seamlessly upgrade it. Moreover, you can easily have valid SSL certificate without ejecting.
    You will need to copy your certificate to node_modules/webpack-dev-server/ssl/server.pem. The downside is that you need to manually copy the file. However, one way to make this seamless is to add a postinstall script that creates a symlink. Here is a script I created:

    #!/bin/bash
    # With create-react-app, a self signed (therefore invalid) certificate is generated.
    # 1. Create some folder in the root of your project
    # 2. Copy your valid development certificate to this folder
    # 3. Copy this file to the same folder
    # 4. In you package.json, under `scripts`, add `postinstall` script that runs this file.
    # Every time a user runs npm install this script will make sure to copy the certificate to the 
    # correct location
    
    TARGET_LOCATION="./node_modules/webpack-dev-server/ssl/server.pem"
    SOURCE_LOCATION=$(pwd)/$(dirname "./local-certificate/server.pem")/server.pem
    
    echo Linking ${TARGET_LOCATION} TO ${SOURCE_LOCATION}
    rm -f ${TARGET_LOCATION} || true
    ln -s ${SOURCE_LOCATION} ${TARGET_LOCATION}
    chmod 400 ${TARGET_LOCATION} # after 30 days create-react-app tries to generate a new certificate and overwrites the existing one. 
    echo "Created server.pem symlink"
    

    Your package.json should look something like:

    "scripts": {
        ...
        "postinstall": "sh ./scripts/link-certificate.sh"
    }
    
    • My solution is based on this thread

提交回复
热议问题