Deploy Express.js: Cloudflare, Telegram & Auto Purge

by Admin 53 views
Deploy Express.js: Cloudflare, Telegram & Auto Purge

Hey there, code wizards! Ever wanted to effortlessly deploy your Express.js applications, automate cache purges, and get notified on Telegram? Well, buckle up because we're diving deep into a handy Bash script, lovingly crafted for the TRYONYOU–ABVETOS–ULTRA–PLUS–ULTIMATUM project, that does all of that and more! This script simplifies the deployment process, integrates with Cloudflare for blazing-fast performance, and keeps you in the loop with Telegram notifications. Let's get started!

Understanding the Script's Purpose and Components

This script, deploy_express_tryonyou.sh, is a complete automation solution designed to streamline the deployment of Express.js applications. It's built with a focus on ease of use and efficiency, tackling common deployment challenges with clever solutions. It automates key tasks such as unzipping application files, installing dependencies, building the application, deploying it to Vercel, purging the Cloudflare cache, and sending a Telegram notification upon successful deployment. The script cleverly uses environment variables for secure access to sensitive information like API tokens, ensuring a safe and reliable deployment process. This script is a lifesaver for anyone looking to automate their deployment workflow. The use of Vercel is pivotal. Vercel is a cloud platform for static sites and serverless functions, and in this context, it allows for easy deployment of the application. Cloudflare is a content delivery network (CDN) that provides caching, security, and performance optimization for websites. Finally, Telegram notifications keep the user informed about the deployment status.

Key Components and their Functions

  1. Environment Variables: The script utilizes environment variables such as VERCEL_TOKEN, CLOUDFLARE_API_TOKEN, CLOUDFLARE_ZONE_ID, TELEGRAM_BOT_TOKEN, and TELEGRAM_CHAT_ID. These variables are used to store sensitive information like API tokens and chat IDs, keeping them separate from the script for security. Make sure you set these up properly, or the script won't work as expected. These environment variables are crucial for the script's functionality, as they hold the API keys and IDs needed for authentication and communication with external services.
  2. Unzipping the Application: The script begins by unzipping the deployment package, which is assumed to be a .zip file located in the specified INBOX directory. This step extracts the application files into a working directory (WORKDIR), preparing them for the next steps.
  3. Dependency Installation & Build: It then navigates to the working directory and runs npm install to install all necessary dependencies, followed by npm run build to build the application. This ensures that the application is ready for deployment.
  4. Vercel Deployment: The script uses vercel --prod to deploy the built application to Vercel. It retrieves the deployment URL and stores it for later use in the Telegram notification.
  5. Cloudflare Cache Purge: If the CLOUDFLARE_API_TOKEN and CLOUDFLARE_ZONE_ID environment variables are set, the script purges the Cloudflare cache using the Cloudflare API. This ensures that the latest version of the application is served to users.
  6. Telegram Notification: Upon successful deployment, the script sends a Telegram notification to a specified chat, including the deployment URL and a timestamp.

Setting up the Prerequisites and Environment

Before you can unleash the power of this script, you need to set up a few things, guys. This ensures a smooth and secure deployment process.

Required Tools and Services

  1. Node.js and npm: You'll need Node.js and npm (Node Package Manager) installed on your system. These are essential for managing your project's dependencies and building the Express.js application.
  2. Vercel Account & CLI: Create a Vercel account and install the Vercel CLI (npm install -g vercel). This tool allows you to deploy your application directly from the command line. Log in using vercel login. You'll use this token in the script.
  3. Cloudflare Account: If you plan to use Cloudflare for caching, you'll need a Cloudflare account and your zone ID and API token. Cloudflare enhances your application's performance by caching your content and distributing it across a global network of servers. Make sure to grab your CLOUDFLARE_API_TOKEN and CLOUDFLARE_ZONE_ID. The API token is used to authenticate your requests to the Cloudflare API, and the zone ID identifies the specific website or application you're managing within Cloudflare.
  4. Telegram Bot: Create a Telegram bot using BotFather and get your TELEGRAM_BOT_TOKEN. You'll also need your Telegram chat ID (TELEGRAM_CHAT_ID). This is how the script will send you notifications. Use the token and chat ID to set up the Telegram notifications.

Configuring Environment Variables

The script relies heavily on environment variables. These are variables that store important configuration data, such as API tokens and other sensitive information, separate from the script's code. This is very important for security and flexibility. You can set these in your shell profile (e.g., ~/.bashrc or ~/.zshrc) or through your CI/CD system. Let's go over each one:

  • VERCEL_TOKEN: Your Vercel API token. This is used to authenticate your deployment requests to Vercel. You can find this in your Vercel account settings.
  • CLOUDFLARE_API_TOKEN: Your Cloudflare API token. This allows the script to purge the Cloudflare cache after deployment, ensuring that users see the latest version of your application. Make sure to create an API token with the necessary permissions (e.g., Zone: Purge).
  • CLOUDFLARE_ZONE_ID: Your Cloudflare zone ID. This identifies the specific website or application you're managing within Cloudflare. You can find this in your Cloudflare dashboard.
  • TELEGRAM_BOT_TOKEN: Your Telegram bot token. This is used by the script to send notifications to your Telegram chat. You get this when you create your bot with BotFather.
  • TELEGRAM_CHAT_ID: Your Telegram chat ID. This is the ID of the chat where you want to receive deployment notifications. You can find this ID by sending a message to your bot and checking the response from the Telegram API.

Make sure to set these environment variables correctly; otherwise, the script will not function as expected. I suggest creating a .env file and loading it before running the script. You can use the source .env command to load them. This keeps things organized.

Deep Dive into the Script: Line by Line Breakdown

Let's break down the script line by line to understand how it works and what each part does. This way, you'll be able to tailor it to your needs.

#!/bin/bash
# ==========================================================
# 🦚 TRYONYOU–ABVETOS–ULTRA–PLUS–ULTIMATUM
# Deploy Express Script v2.2 – Cloudflare Auto Purge
# ==========================================================

INBOX=~/Library/Mobile\ Documents/com~apple~CloudDocs/TRYONYOU_DEPLOY_EXPRESS_INBOX
WORKDIR="$INBOX/_deploy_build"
LOGFILE="$INBOX/deploy_log_$(date +%Y%m%d_%H%M).log"
  • The script begins with the shebang #!/bin/bash, specifying that it should be executed using the Bash interpreter. The script then defines the deployment environment, including the inbox location, the working directory, and the log file. The INBOX variable specifies the directory where the deployment package (.zip file) is located. The WORKDIR variable specifies the directory where the files will be extracted and built. The LOGFILE variable specifies the file where logs will be written. This is super helpful for debugging!
echo "🦚 Starting Deploy Express..."
mkdir -p "$WORKDIR"
cd "$INBOX"
  • This part outputs a starting message and creates the necessary directories, setting up the environment for the deployment process. First, it echoes a starting message to the console. Then, mkdir -p "$WORKDIR" creates the working directory if it doesn't already exist. The -p option ensures that parent directories are also created if necessary. Finally, cd "$INBOX" changes the current directory to the inbox, where the deployment package is located.
for f in *.zip; do
  echo "📦 Descomprimiendo $f ..." | tee -a "$LOGFILE"
  unzip -o "$f" -d "$WORKDIR" >> "$LOGFILE" 2>&1
done
  • This is the file extraction loop. It iterates through all .zip files in the inbox directory, unzipping each one into the working directory. It uses a loop to iterate through all zip files. For each file, it outputs a message indicating which file is being unpacked. The unzip -o "$f" -d "$WORKDIR" command extracts the contents of the zip file into the working directory. The -o option tells unzip to overwrite existing files. The >> "$LOGFILE" 2>&1 redirects both standard output and standard error to the log file.
cd "$WORKDIR"
npm install >> "$LOGFILE" 2>&1
npm run build >> "$LOGFILE" 2>&1
  • Here, it navigates into the working directory and installs the dependencies and builds the application. First, it changes the current directory to the working directory. Then, npm install installs all the dependencies listed in the package.json file. Finally, npm run build executes the build script defined in the package.json file, which typically compiles the code and prepares the application for deployment.
vercel --prod --confirm --token=$VERCEL_TOKEN >> "$LOGFILE" 2>&1
DEPLOY_URL=$(vercel ls --token=$VERCEL_TOKEN | head -2 | tail -1 | awk '{print $2}')
echo "🌐 URL final: $DEPLOY_URL" | tee -a "$LOGFILE"
  • This segment handles the deployment of the application to Vercel and retrieves the deployment URL. The vercel --prod --confirm --token=$VERCEL_TOKEN command deploys the application to Vercel in production mode. The --confirm flag automatically confirms any prompts. The --token=$VERCEL_TOKEN option provides the Vercel API token for authentication. The script captures the deployment URL using vercel ls. This command lists all deployments associated with your Vercel account. Then, it uses head -2 | tail -1 to select the second line from the output, which contains the most recent deployment information. awk '{print $2}' extracts the deployment URL. Finally, it echoes the deployment URL to the console and logs it.
# 🧹 Purga automática de caché Cloudflare
if [ -n "$CLOUDFLARE_API_TOKEN" ] && [ -n "$CLOUDFLARE_ZONE_ID" ]; then
  echo "🧹 Purging Cloudflare cache..." | tee -a "$LOGFILE"
  curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$CLOUDFLARE_ZONE_ID/purge_cache" \
       -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
       -H "Content-Type: application/json" \
       --data '{"purge_everything":true}' >> "$LOGFILE" 2>&1
  echo "✅ Cloudflare cache purged." | tee -a "$LOGFILE"
else
  echo "⚠️ Cloudflare environment variables not found — skipping purge." | tee -a "$LOGFILE"
fi
  • This part conditionally purges the Cloudflare cache if the necessary environment variables are set. The if statement checks if both CLOUDFLARE_API_TOKEN and CLOUDFLARE_ZONE_ID are set. If both are set, the script sends a POST request to the Cloudflare API to purge the entire cache. It uses curl to make the API call, specifying the API token in the Authorization header and the content type as application/json. The --data '{"purge_everything":true}' option tells the Cloudflare API to purge the entire cache. The script then echoes a success message. If either of the Cloudflare environment variables is not set, the script skips the cache purge and outputs a warning message.
# 📢 Notificación Telegram
curl -s -X POST "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/sendMessage" \
  -d chat_id="$TELEGRAM_CHAT_ID" \
  -d parse_mode="Markdown" \
  -d text="✅ *TRYONYOU–ABVETOS–ULTRA–PLUS–ULTIMATUM* desplegado y cache purgada.\n🌐 [Abrir en navegador]($DEPLOY_URL)\n🕓 $(date '+%Y-%m-%d %H:%M')" \
  >> "$LOGFILE" 2>&1
  • The Telegram notification system alerts you of the deployment status. The script uses curl to send a POST request to the Telegram API. It includes the bot token, chat ID, and the message content. The parse_mode="Markdown" option allows you to format the message using Markdown. The message includes a success indicator, a link to the deployed application, and a timestamp.
echo "✅ Deploy + Cache Purge + Telegram Notification completado." | tee -a "$LOGFILE"
  • Finally, the script outputs a success message indicating that the entire process has been completed. This message is also logged to the log file.

Customizing and Extending the Script

This script is pretty solid, but you might want to tweak it to fit your exact needs. Here are some ideas to help you out.

Customization Options

  1. Deployment Package: The script assumes your deployment package is a .zip file. You can modify the file extension or add support for other formats (like .tar.gz) by adjusting the for f in *.zip loop.
  2. Working Directory: The WORKDIR variable determines where the application files are extracted and built. You can change this to suit your project structure. Make sure the directory exists or add a mkdir command.
  3. Build Commands: The script uses npm install and npm run build. You can modify these commands if your project uses different build processes or package managers (e.g., yarn install, pnpm install).
  4. Vercel Configuration: The script deploys to Vercel using the --prod flag. You can adjust this to deploy to a different environment (e.g., --staging) or add other Vercel-specific options.
  5. Cloudflare Settings: You can modify the cache purge settings. For example, you can target specific URLs or use different purge methods provided by the Cloudflare API.
  6. Telegram Notifications: Change the message content or add more details in the Telegram notification. You can include information about the build process, deployment errors, or any other relevant information.

Advanced Extensions

  1. Error Handling: Add error handling to gracefully manage failures during the deployment process. You can check the exit codes of commands and send error notifications via Telegram.
  2. Rollback Mechanism: Implement a rollback mechanism to revert to a previous deployment if the current deployment fails. This could involve keeping track of previous deployments and redeploying them if necessary.
  3. Automated Testing: Integrate automated testing into the script. Run tests after building the application and before deploying it to production. Send notifications if tests fail.
  4. Secrets Management: Use a secrets management tool to securely store and manage sensitive information like API tokens and other credentials. Consider using tools like Vault or AWS Secrets Manager.

Troubleshooting Common Issues

Even with a well-crafted script, things can go wrong. Here's a quick guide to help you troubleshoot some common issues.

  1. Incorrect Environment Variables: Make sure all your environment variables are correctly set. Double-check for typos and that the values are accurate. Remember, the script uses VERCEL_TOKEN, CLOUDFLARE_API_TOKEN, CLOUDFLARE_ZONE_ID, TELEGRAM_BOT_TOKEN, and TELEGRAM_CHAT_ID.
  2. Permissions: Ensure that the script has the necessary permissions to execute commands and access the required directories. The user running the script needs read and write access to the inbox, working directory, and log file locations.
  3. Network Connectivity: Verify that your server has internet access. The script needs to connect to Vercel, Cloudflare, and Telegram APIs. Check your network configuration and firewall rules.
  4. Vercel Errors: Review the output of the vercel command in the log file. Vercel often provides detailed error messages that can help you diagnose deployment issues.
  5. Cloudflare API Errors: If you're having trouble with the Cloudflare cache purge, check the Cloudflare API response in the log file for any error messages. Make sure your API token has the correct permissions (Zone: Purge). Also, check if your zone ID is correct.
  6. Telegram Notifications: Make sure your Telegram bot is set up correctly and that the chat ID is accurate. You can test the Telegram notification by sending a test message directly to your bot using the Telegram API or a testing tool like Postman.
  7. Log Files: The log file ($LOGFILE) is your best friend. Check the log file for errors, warnings, and detailed output from each step of the script. This will help you pinpoint the source of any problems.
  8. Dependencies: Ensure all the necessary dependencies are installed correctly in your package.json file. Run npm install to make sure you have all the necessary packages.

Conclusion: Automate, Deploy, and Relax!

There you have it, guys! A powerful and flexible script to streamline your Express.js deployments. By automating the deployment process, integrating with Cloudflare, and receiving Telegram notifications, you can save time, reduce errors, and focus on what matters most: coding. This script is designed to be easily adaptable, so go ahead and customize it to suit your needs. Remember to set up your environment variables correctly, and you'll be well on your way to smooth, automated deployments. Happy coding, and enjoy the TRYONYOU–ABVETOS–ULTRA–PLUS–ULTIMATUM! Deploy with confidence, knowing you've got a reliable system in place. Now go forth and conquer the cloud!