]}]} />/g

Introduction

When you publish a blog post, when a build is completed, when there”s an important system update——it”s tedious to manually post to SNS every time at those timings, isn”t it?

User

Days of posting by remembering, ‘Oh, I have to’ announce on Twitter”… On late-night deploys, I sometimes even forgot.

I myself, when I was operating a Web app in personal development, was posting manually for every deploy, and a follower told me, ‘I didn’t notice the update,” and I finally felt the necessity of automation.

In this article, I will practically explain how to automate SNS notifications by acquiring X (formerly Twitter) API keys and setting them as environment variables. I will proceed step-by-step while pushing through points where it’s easy to get stuck, from operations on the Developer Portal to actual code implementation.

”Automation of Notification” Brought by X API Integration

Automation of SNS notifications has value beyond simple “reduction of posting effort.”

First, optimization of posting timing is realized. Since notifications are sent simultaneously with article publication or system update, followers can catch information in real-time. With manual posting, people tend to procrastinate, thinking “I”ll post them all later,” but if automated, it is announced reliably at that moment.

Next, consistency of notification content is maintained. With manual, the wording may waver or important information may be forgotten depending on the mood or fatigue level of the day, but using an automated template ensures that the post always contains necessary information.

💡 Operation during late-night or early morning also becomes possible

When operating a global service, there may be cases where you want to announce updates for overseas users in the middle of the night Japan time. If automated, you can notify at the optimal timing without worrying about time zones.

From developers who have actually introduced API integration, I often hear voices like “Forgotten notifications are gone” and “Released from the stress of posting.” Once set up, the system will continue to move automatically thereafter.

Step 1: X Developer Account and App Creation

To use X API, registration of a developer account and creation of an app are necessary first.

Accessing the Developer Portal

Access the X Developer Portal (developer.twitter.com or developer.x.com) and log in with the X account you usually use. If it’s your first time using the Developer Portal, a screen to input basic information such as the purpose of use may be displayed.

⚠️ Be honest about the purpose of use

What’s important here is to honestly describe the purpose of use . Writing specifically like “Update notification of personal blog” or “Build notification of open-source project” will result in smooth approval. Avoid vague descriptions or expressions that could be misunderstood as commercial use.

Creating a New App

Once you enter the developer dashboard, create a new app from the “Projects & Apps” section. Click the “Create App” button and enter the app name and a brief description.

The app name can be changed later, but giving it an easy-to-understand name will make management easier. For example, names where the use is obvious at a glance, such as “MyBlog Notifier” or “Deploy Alert Bot,” are recommended.

Upon completion of creation, the dashboard screen of the app is displayed. From here, proceed to acquire API keys and tokens.

Step 2: Acquiring the 4 Keys and Tokens

To use X API, the following 4 authentication information are necessary.

The 4 values to acquire

  • API Key (Consumer Key): The public key to identify the app itself
  • API Secret Key (Consumer Secret): The private key of the app
  • Access Token : Token to identify the user (you)
  • Access Token Secret : The private key of the user token

These each have different roles, and only when all of them are揃う (complete) does posting via API become possible.

Operations in the Keys and Tokens section

Open the “Keys and Tokens” tab from the app dashboard. There are two sections here: “Consumer Keys” and “Authentication Tokens.”

In the Consumer Keys section, API Key and API Secret Key are displayed. They are already generated for the first time, but re-issuance is also possible with the “Regenerate” button. However, note that re-issuing will invalidate old keys, so if they are used in existing systems, caution is needed.

In the Authentication Tokens section, click the “Generate” button to generate Access Token and Access Token Secret.

📝 Tokens are displayed only once

Because the generated tokens are displayed only once , please make sure to copy and save them in a safe place at this timing. Voices from users who actually used say, “I forgot to take note of the token and ended up having to re-issue,” so I recommend saving it to a text file, etc. as soon as it”s displayed.

Security Precautions

These 4 values are important authentication information that has the authority to post as your account. Pay attention to the following points.

  • Do not commit to public repositories such as GitHub
  • Sharing within a team should be done by encrypted methods
  • Keep security by re-issuing regularly
  • Delete unused apps

Especially mis-committing to GitHub is a frequent trouble. Be sure to do the .gitignore settings described later.

Step 3: Setting to Environment Variables (.env)

Set the acquired 4 values as environment variables to use them safely in the project.

Creating the .env file

Create a .env file in the root directory of the project and describe as follows.

TWITTER_API_KEY="your_api_key_here"
TWITTER_API_SECRET="your_api_secret_here"
TWITTER_ACCESS_TOKEN="your_access_token_here"
TWITTER_ACCESS_SECRET="your_access_secret_here"
TWITTER_BEARER_TOKEN="your_bearer_token_here"

Replace the actual values with the keys and tokens you just acquired. Comment lines (lines starting with #) are convenient to leave so that you can understand what setting it is when you look at it later.

Adding to .gitignore

Because the .env file contains sensitive information, you must not commit it to version control systems. Add the following to the .gitignore file.

.env
.env.local
.env.*.local

This will make Git ignore the .env file. If you have already committed by mistake, GitHub’s secret scanning feature may issue a warning. In that case, re-issue the keys immediately and remove them from the history as well.

Variations in Environment Variable Names

Depending on the library or framework used, environment variable names may differ. For example, names like TWITTER_API_KEY or CONSUMER_KEY may be used.

Check the official documentation or the README of the library, and set according to the required environment variable names. If you use multiple libraries, you can also prepare variables corresponding to each.

Step 4: Implementation Example in Node.js

Let’s see how to actually read environment variables from code and post to X. Here I introduce an example using Node.js and the twitter-api-v2 library.

Installing Necessary Packages

First, install the necessary packages.

npm install twitter-api-v2 dotenv

dotenv is a package to read environment variables. By using this, the contents of the .env file become available via process.env.

Basic Posting Code

Below is basic code to post to X using environment variables.

require("dotenv").config();
const { TwitterApi } = require("twitter-api-v2");

const client = new TwitterApi({
  appKey: process.env.X_API_KEY,
  appSecret: process.env.X_API_SECRET,
  accessToken: process.env.X_ACCESS_TOKEN,
  accessSecret: process.env.X_ACCESS_SECRET,
});

async function notifySNS(text) {
  try {
    const result = await client.v2.tweet(text);
    console.log("Post successful: ", result.data.id);
  } catch (error) {
    console.error("Post failed: ", error);
  }
}

// Example use
notifySNS("Blog updated! Please check the new article.");

This code can post specified text just by calling the notifySNS function. If called from build scripts or deploy hooks, auto-notification is realized.

Example Notification on Build Completion

When incorporating into actual build scripts, ‘do as follows.

const { execSync } = require("child_process");

async function buildAndNotify() {
  try {
    // Run build
    console.log("Starting build...");
    execSync("npm run build", { stdio: "inherit" });

    // Notify on build success
    const buildTime = new Date().toLocaleString("ja-JP");
    await notifySNS(
      `✅ Build completed\n⏰ ${buildTime}\n🚀 Deploying the latest version`,
    );

    console.log("Notification completed");
  } catch (error) {
    // Also notify on build failure
    await notifySNS(`❌ Build failed\nPlease check logs for details`);
    throw error;
  }
}

buildAndNotify();

By using emojis, it becomes easy to stand out on the timeline and judge success/failure. From users who are actually operating in this pattern, it is well-received as “visually easy to understand.”

More Advanced Application Example

In the case of article publication, posts including the title and URL are effective.

async function notifyArticle(title, url, tags) {
  const hashtags = tags.map((tag) => `#${tag}`).join(" ");
  const text = `📝 Published a new article!\n\n"${title}"\n\n${url}\n\n${hashtags}`;

  await notifySNS(text);
}

// Example use
notifyArticle(
  "Realize Auto-notification with X API Integration",
  "https://example.com/articles/x-api-guide",
  ["programming", "API", "automation"],
);

In this way, notification content can be customized according to the situation.

Checkpoints Before Introduction

Check the following points beforehand for smooth introduction.

Checking API Usage Limits

X API has free plans and paid plans, each with limits on the number of posts and features. Choose a plan that suits your use.

Even with a free plan, it can sufficiently respond to things like personal blog update notifications or build notifications. However, note that if you post a large amount in a short time, you may hit limits, so attention is needed on posting frequency.

Preparing the Development Environment

When using Node.js, version 14 or later is recommended. Check the current version with the node -v command, and if it’s old, update it.

Also, if you are not used to handling .env files, I recommend checking the operation in a test environment first. If you try it for the first time in a production environment and fail, troubleshooting becomes difficult.

Preparing Error Handling

API calls may fail due to network errors or rate limits. As in the previous code example, be sure to catch errors with try-catch and process them appropriately.

Especially when incorporating into CI/CD pipelines, behavior at the time of error needs to be considered so that the entire build doesn’t stop with a notification failure.

Re-confirming Security Measures

Leakage of environment variables has a risk of being posted as your account by a third party. Re-confirm the following.

  • Whether .env is included in .gitignore
  • Whether production environments have environment variables as server settings
  • Whether you are using safe methods if sharing keys within a team

Especially when using hosting services such as Vercel or Netlify, check the method of setting environment variables from the management screen.

Troubleshooting: Common Failures and Countermeasures

Actual introduction often results in points where many people get stuck.

”Unauthorized” error occurs

This happens when authentication information is wrong or authority is insufficient. Check the following.

  • Whether environment variable values are copied correctly (whether extra spaces or line breaks are included)
  • Whether Access Token and Access Token Secret are paired correctly
  • Whether “Read and Write” is enabled in the app”s permission settings
💡 Confirm permission settings

Permission settings can be changed from app settings on the Developer Portal. Since it may be “Read Only” by default, if you use the posting feature, make sure to change it to “Read and Write.”

Environment variables are not read

If process.env.X_API_KEY becomes undefined, try the following.

  • Whether require("dotenv").config() is written at the beginning of the code
  • Whether the .env file is in the root directory of the project
  • Whether the file name is accurately .env (whether it’s not something like .env.txt)

In the case of Windows, extensions might be hidden in Explorer. Run the dir command in Command Prompt or PowerShell to check the file name.

Hitting Rate Limits

If you post a large number in a short time, a “Too Many Requests” error occurs. In this case, consider the following countermeasures.

  • Open intervals between posts (at least several seconds or more)
  • Nnarrow down to only important notifications
  • Consider upgrading to a paid plan

In the case of build notifications, an operation can also be considered such as notifying only on success and checking on failure in logs.

”Notification Reform” Brought by X API Integration

Auto-notification by API integration greatly changes the development flow and the way of information transmission.

Improvement of Working Efficiency

By eliminating the time for manual posting, you can concentrate on development and content creation. Each post takes only a few minutes, but it will be a big time saving if piled up.

A personal developer says, “I was doing update notification manual about 10 times a week, but automation saved about 2 hours of time a month.” By allocating this time to development of new features, the quality of service improved.

Consistency of Notification Quality

Templated notifications always contain necessary information, and the brand image is also unified. With manual, wavering occurs as “I”m tired today, so concisely” or “I”ll write in detail today,” but with automation, there is no such concern.

24/7 Operation

Since notifications are sent automatically even at night, early morning, or on holidays, it also responds to global followers. This is a big merit for personal developers.

Effect on Mental Health

Release from the pressure of “I have to post” is also a merit that cannot be overlooked. Especially perfectionists tend to worry about the timing or wording of a post, but automation eliminates such stress.

Deep Dive: Binary Upload for Multiple Media

To attach images rather than just posting text, a 2-step process of “uploading” and “associating” is required.

// Flow of posting images using twitter-api-v2
async function postWithImage(text, imagePath) {
  // 1. Upload media (Using v1.1 API)
  const mediaId = await client.v1.uploadMedia(imagePath);

  // 2. Associate with tweet (Using v2 API)
  await client.v2.tweet({
    text: text,
    media: { media_ids: [mediaId] }
  });
}

This “correct usage of API versions” is the most common technical stumbling block in X API integration.

Summary

I have explained the series of flow from X API environment variable setting to auto-notification implementation.

Creating an app on the Developer Portal, acquiring the 4 keys and tokens. Saving them safely in a .env file and reading them from code to post——anyone can realize auto-notification if they push through this basic flow.

At first, you may feel “it seems difficult,” but once you set it up, the system will continue to move automatically thereafter. By automating all notifications such as blog updates, build completions, system alerts, etc., your time should be able to be used for more valuable work.

Please start small first. Confirm operation with test posts and gradually incorporate into the production environment. By doing so, you can receive the benefits of auto-notification safely and reliably.

Reference Information