Search code examples
reactjsbashcreate-react-appsource-mapssentry

How to automatically create a Sentry release and upload source-maps to Sentry in a react project?


I have a create-react-app project, and I'd like the deploy process to generate a Sentry release and upload the source maps to Sentry as well.


Solution

  • This script will create a Sentry release for version specified in the package.json file, and upload the source maps to Sentry.

    It will work for any JS project, not just React.

    create a file in your project root and name it deploy.sh:

    SENTRY_TOKEN="YOUR_TOKEN"
    PACKAGE_VERSION=`cat package.json \
      | grep version \
      | head -1 \
      | awk -F: '{ print $2 }' \
      | sed 's/[",]//g' \
      | tr -d '[[:space:]]'`
    
    printf "\nBuilding version $PACKAGE_VERSION...\n\n"
    
    #2) Build for dev and cd to build directory
    npm run build # or whatever your build command is
    cd build/static/js # or whatever your build folder is
    
    #3) create Sentry release
    SOURCE_MAP=`find . -maxdepth 1 -mindepth 1 -name '*.map' | awk '{ gsub("./", "") ; print $0 }'`
    printf "\nCreating a Sentry release for version $PACKAGE_VERSION...\n"
    
    curl https://sentry.io/api/0/projects/:sentry_organization_slug/:sentry_project_slug/releases/ \
      -X POST \
      -H "Authorization: Bearer ${SENTRY_TOKEN}" \
      -H 'Content-Type: application/json' \
      -d "{\"version\": \"${PACKAGE_VERSION}\"}" \
    
    #4) Upload a file for the given release
    printf "\n\nUploading sourcemap file to Sentry: ${SOURCE_MAP}...\n"
    curl "https://sentry.io/api/0/projects/:sentry_organization_slug/:sentry_project_slug/releases/$PACKAGE_VERSION/files/" \
      -X POST \
      -H "Authorization: Bearer ${SENTRY_TOKEN}" \
      -F file=@${SOURCE_MAP} \
      -F name="https://THE_URL_OF_THE_MAIN_JS_FILE/$SOURCE_MAP"
    
    #5) IMPORTANT: Delete the sourcemaps before deploying
    rm $SOURCE_MAP
    
    #6) upload to your cloud provider
    ...
    

    replace:

    1. :sentry_organization_slug and :sentry_project_slug with the correct values from sentry (from the URL of any page inside your sentry account website)
    2. SENTRY_TOKEN with your token from Sentry
    3. THE_URL_OF_THE_MAIN_JS_FILE with the URL where your react build file is publicly accessible.

    run.

    Make sure you don't forget to update the package.json version on every release