Build a
LINE bot with
Node.js on Container Apps
Create a LINE Official Account bot step by step, with HTTPS and scale to zero when nobody is chatting
On this page
- What you need
- What a webhook bot is
- Create the
LINE Official Account and channel
- Write the bot
- Test on your computer
- Push the code to
GitHub
- Deploy on Container Apps
- Step 1: Source
- Step 2: Configuration
- Step 3: Review & deploy
- Set the webhook in
LINE
- Costs and the free quota
- Common problems
- Change the bot and redeploy
- Turn it into a small JSON API
- Where to go next
- Frequently asked questions
You can run your own LINE bot from one Node.js file and a short Dockerfile on XVer Container Apps, giving you an HTTPS webhook URL that scales to zero when nobody is chatting. There is no server to leave running and no SSL certificate to configure yourself.
When you finish, you message the bot ping and it answers pong; you message hours and it replies with the shop's opening hours. From there you can change the answers to fit your own business.
What you need#
- A
LINE OA that answers by itself with the replies you set
- An HTTPS URL to use as the webhook
- Your own API to build on from the same code
Before you start
You do not need Docker on your computer, because XVer builds the image from GitHub for you.
What a webhook bot is#
A webhook is a URL that LINE calls whenever someone messages your account. The bot reads the message and calls LINE's API to reply. When nobody is messaging, the bot has nothing to do.
- A customer messages your
LINE OA, for example typing hours
LINE calls the webhook and sends the data with a signature to your URL
- Container Apps starts an instance if it has scaled to 0
- The bot checks the signature and answers
LINE with 200
- The bot calls the Reply API and the customer sees the answer
Min replicas 0Recommended
No requests means no instances, so no vCPU or memory charge. The first message after a quiet spell waits for an instance to start, which is called a cold start. Suits bots that get messages in bursts.
Min replicas 1 or more
An instance is always ready, so there is no cold start from scaling to 0. You pay for vCPU and memory every second it runs. Suits bots that must answer every message instantly.
Create the
LINE Official Account and channel#
You can no longer create a Messaging API channel directly in the LINE Developers Console; you start from a LINE Official Account (official steps (opens in a new tab)). Menu names may differ depending on your language setting.
- Create a
LINE Official Account. Register a Business ID and fill in the account sign-up form (opens in a new tab).
- Turn on the Messaging API. In
LINE Official Account Manager (opens in a new tab), pick the account, go to Settings and enable the Messaging API. The first time, it asks for a developer name and email.
- Pick a provider. This is the owner of the account, such as your shop name. Choose carefully; it cannot be changed later.
- Open the
LINE Developers Console. Sign in at developers.line.biz/console (opens in a new tab) with the same account, pick the provider, then the channel you just created.
- Find two values: the Channel secret on the Basic settings tab, and the Channel access token (long-lived) on the Messaging API tab. Click Issue to create the token.
The channel secret proves a webhook really came from LINE. The access token lets the bot send messages. A long-lived token never expires, and each channel can have one (token docs (opens in a new tab)).
Write the bot#
Create a new folder called line-bot with these files.
- line-bot/
- server.js
- package.json
- Dockerfile
- test.mjs
import { createHmac, timingSafeEqual } from 'node:crypto';
import { createServer } from 'node:http';
const port = Number(process.env.PORT) || 8080;
const secret = process.env.LINE_CHANNEL_SECRET;
const token = process.env.LINE_CHANNEL_ACCESS_TOKEN;
if (!secret || !token) {
console.error('missing LINE_CHANNEL_SECRET or LINE_CHANNEL_ACCESS_TOKEN');
process.exit(1);
}
// Read the body as raw bytes; never parse it before checking the signature
async function readBody(req) {
const chunks = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (size > 1024 * 1024) throw new Error('body too large');
chunks.push(chunk);
}
return Buffer.concat(chunks);
}
function validSignature(rawBody, header) {
if (typeof header !== 'string') return false;
const expected = createHmac('sha256', secret).update(rawBody).digest();
const received = Buffer.from(header, 'base64');
return received.length === expected.length && timingSafeEqual(received, expected);
}
// Edit the bot's answers here
function answer(text) {
const t = text.trim().toLowerCase();
if (t === 'ping') return 'pong';
if (t === 'hours') return 'Open every day, 10:00 to 20:00.';
return `You wrote: ${text.slice(0, 500)}`;
}
async function handleEvent(event) {
if (event.type !== 'message' || event.message?.type !== 'text' || !event.replyToken) return;
const res = await fetch('https://api.line.me/v2/bot/message/reply', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
body: JSON.stringify({
replyToken: event.replyToken,
messages: [{ type: 'text', text: answer(event.message.text) }],
}),
signal: AbortSignal.timeout(10_000),
});
console.log('reply status', res.status);
if (!res.ok) console.error(await res.text());
}
function send(res, status, data) {
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify(data));
}
const pending = new Set();
const server = createServer(async (req, res) => {
try {
const { pathname } = new URL(req.url, 'http://localhost');
if (req.method === 'GET' && pathname === '/') return send(res, 200, { ok: true });
if (req.method !== 'POST' || pathname !== '/webhook') return send(res, 404, { error: 'not found' });
const rawBody = await readBody(req);
if (!validSignature(rawBody, req.headers['x-line-signature'])) {
console.warn('rejected: bad signature');
return send(res, 401, { error: 'bad signature' });
}
const { events = [] } = JSON.parse(rawBody.toString('utf8'));
console.log('accepted events', events.length);
send(res, 200, { ok: true }); // Answer LINE first, then send the replies
for (const event of events) {
const job = handleEvent(event).catch(console.error).finally(() => pending.delete(job));
pending.add(job);
}
} catch (err) {
console.error(err.message);
if (!res.headersSent) send(res, 400, { error: 'bad request' });
}
});
server.listen(port, '0.0.0.0', () => console.log(`listening on ${port}`));
// When the platform stops the instance, finish sending pending replies first
process.on('SIGTERM', () => {
server.close(async () => {
await Promise.allSettled(pending);
process.exit(0);
});
});Three things in this code are worth knowing.
Check the signature first
Compute HMAC-SHA256 over the raw body with the channel secret and compare it with the x-line-signature header. If you parse the JSON first, characters can change and the signature will not match (LINE docs (opens in a new tab)).
Compare in constant time
timingSafeEqual takes the same time wherever the mismatch is, so nobody can guess the signature from response times.
Answer 200 first
LINE recommends processing events asynchronously, so the response does not wait for the Reply API.
{
"name": "line-bot",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": { "start": "node server.js" },
"engines": { "node": ">=24" }
}FROM node:24-slim
WORKDIR /app
ENV NODE_ENV=production
COPY package.json server.js ./
USER node
EXPOSE 8080
CMD ["node", "server.js"]The app listens on the port from the PORT variable, or 8080 if it is not set, which matches the default Container port in XVer.
Test on your computer#
This file generates a temporary secret, starts the bot, and sends requests with a real and a fake signature, so you do not need any values from LINE. It works on Windows,
macOS and
Linux.
import { spawn } from 'node:child_process';
import { createHmac, randomBytes } from 'node:crypto';
const secret = randomBytes(16).toString('hex');
const app = spawn(process.execPath, ['server.js'], {
env: { ...process.env, PORT: '8090', LINE_CHANNEL_SECRET: secret, LINE_CHANNEL_ACCESS_TOKEN: 'local-test' },
stdio: ['ignore', 'pipe', 'inherit'],
});
await new Promise((resolve, reject) => {
app.stdout.once('data', resolve);
app.once('exit', () => reject(new Error('server.js stopped')));
});
const body = JSON.stringify({ destination: 'test', events: [] });
const good = createHmac('sha256', secret).update(body).digest('base64');
async function check(name, want, payload, signature) {
const headers = signature ? { 'x-line-signature': signature } : {};
const res = await fetch('http://127.0.0.1:8090/webhook', { method: 'POST', headers, body: payload });
console.log(res.status === want ? 'PASS' : 'FAIL', res.status, name);
}
await check('valid signature', 200, body, good);
await check('wrong signature', 401, body, 'wrong');
await check('no signature', 401, body);
await check('body tampered with', 401, body + ' ', good);
app.kill();node test.mjsYou should see this. Lines saying rejected: bad signature appear in between, which is correct.
PASS 200 valid signature
PASS 401 wrong signature
PASS 401 no signature
PASS 401 body tampered withPush the code to
GitHub#
Create an empty repository called line-bot on GitHub (private is fine) and enter your username here. Come back for SERVICE_URL after you deploy.
Type your own values and the commands on this page follow
git init -b main
git add server.js package.json Dockerfile test.mjs
git commit -m "LINE bot"
git remote add origin https://github.com/GITHUB_USER/line-bot.git
git push -u origin mainDeploy on Container Apps#
Sign in at my.xver.cloud and open Container Apps. The first time, click Activate Container Apps, then click Deployment. The form has three steps: Source, Configuration and Review & deploy.


Step 1: Source#
Set the Service name, such as my-line-bot, choose Request-based as the Pricing model, then choose the source. The pricing model cannot be changed later; you would have to create a new container.


GitHub repository
- Choose
GitHub repository and click Connect GitHub. Allow the GitHub App to see the
line-botrepo. - Pick the Owner and Repository, and set Branch to
main. - The Dockerfile path is
Dockerfile. Click Preview Dockerfile to confirm the file can be read.
This option is available when you own the project in XVer.
Container image
If you have an image on Docker Hub or GHCR, choose Container image and enter the image name and Image tag. For a private image, add a Registry credential first.
If you build it yourself, target linux/amd64, especially on an Apple Silicon Mac, and run docker login ghcr.io first. The username in the image name must be lowercase.
docker build --platform linux/amd64 -t ghcr.io/GITHUB_USER/line-bot:1.0.0 .
docker push ghcr.io/GITHUB_USER/line-bot:1.0.0When it works, the last line shows digest: sha256:....
To keep the image in Thailand with XVer instead, see how to push to Artifact Registry and run it on Container Apps.
Step 2: Configuration#


| Field | Value | Note |
|---|---|---|
| Container port | 8080 | Matches the app |
| CPU (m) | 250 | Equals 0.25 vCPU. The default is 1000, so change it |
| Memory (MB) | 512 | 0.5 GiB |
| Request timeout (s) | 30 | This bot answers fast; no need to wait long |
| Request concurrency | 50 | Default |
| Min replicas | 0 | Allows scaling to 0 |
| Max replicas | 1 | Keeps the budget in check at first; raise it later |
Under Environment variables, click Add variable twice.


| NAME | value |
|---|---|
LINE_CHANNEL_SECRET |
Paste the channel secret from |
LINE_CHANNEL_ACCESS_TOKEN |
Paste the channel access token from |
Do not add PORT, and do not wrap values in quotes or spaces.
Step 3: Review & deploy#
Check CPU, Memory and Replicas in the summary, accept the terms, then click Deploy container. Wait until the status is ready. You can follow the build on the Builds tab.
On the Overview tab, copy the Default URL. It starts with the service name, followed by a generated name, ends in .apps.xver.dev, and already has HTTPS, for example https://my-line-bot-quiet-harbor-4tn8w2xk9qbz.apps.xver.dev. Put the host into the SERVICE_URL field above.


Test both the health endpoint and the webhook route with a fake signature.
curl -i https://SERVICE_URL/
curl -i -X POST https://SERVICE_URL/webhook -H 'x-line-signature: wrong' -d '{"events":[]}'Set the webhook in
LINE#
The URL ends with /webhook.
https://SERVICE_URL/webhook- Enter the URL. In the
LINE Developers Console, open the Messaging API tab. At Webhook URL, click Edit, paste the URL, then click Update.
- Click Verify. You should see Success. If the first try times out because of a cold start, click it again.
- Turn on Use webhook.
- Turn off auto-replies. On the same tab, click Edit next to Auto-reply messages and set it to Disabled in
LINE Official Account Manager. Otherwise customers may get two answers. Greeting messages can stay on or off as you like.
- Add the bot as a friend and message it. Scan the QR code on the Messaging API tab and type
ping. You should getpong.
Costs and the free quota#
Each container gets a monthly free quota of 180,000 vCPU-seconds, 360,000 GiB-seconds and 1,000,000 HTTP requests, reset on the 1st of every month.
Example setup: one instance at 0.25 vCPU and 0.5 GiB, running 150 hours a month and taking 300,000 requests.
| Item | How it is counted | Used | Free quota |
|---|---|---|---|
| vCPU | 0.25 × 150 × 3,600 | 135,000 vCPU-seconds | 180,000 |
| Memory | 0.5 × 150 × 3,600 | 270,000 GiB-seconds | 360,000 |
| Requests | As they arrive | 300,000 | 1,000,000 |
vCPU, memory and requests at this size add up to ฿0. To find the free ceiling, take the vCPU-second quota ÷ 0.25 ÷ 3,600 and the GiB-second quota ÷ 0.5 ÷ 3,600, and use the smaller result.
| Case | Effect on cost |
|---|---|
| Two instances running at once for an hour | Counts as two hours |
| An instance idling before it scales down | May be counted too, so a bot messaged throughout the day uses more hours than its processing time |
| Going over the quota | You pay only the excess of each item, deducted from credit |
| Min replicas 1 for 30 days (720 hours) | Uses 648,000 vCPU-seconds and 1,296,000 GiB-seconds, for ฿74.88 in total |
| Block Storage and outbound traffic | Not included in this example; Block Storage has no free quota |
Once it is live, watch the Free quota and Cost cards on the container page and keep your credit topped up. A container is deleted when credit runs out and the 24-hour grace period passes.
Common problems#
The Logs tab shows output only while the container is running. Message the bot once to wake it, then click Start.
Build and deploy issues on XVer
IssueBuild failed
The Dockerfile was not found or the branch name is wrong. Check the Builds tab, the Branch, and the Dockerfile path.
IssueDeploy failed with missing LINE_...
One or both environment variables are missing. Open the Settings tab, add both variables, and click Save changes.
IssueDeploy failed even though the app started
There is a port mismatch. Set Container port to 8080.
Issueexec format error in logs
The image is not built for linux/amd64. Rebuild and push with --platform linux/amd64.
Webhook verify and LINE reply issues
IssueVerify returns 401
The channel secret is wrong or came from another channel. Copy it again from Basic settings.
IssueVerify returns 404
/webhook is missing at the end of the Webhook URL. Update the URL in LINE Developers Console.
IssueVerify times out
Likely a cold start or a crashed service. Click Verify again; if it still fails, check the container status.
IssueVerify passes but the bot stays silent
Use webhook is still turned off. Enable it and send another test message.
IssueLogs show reply status 401
The channel access token is wrong or has been revoked. Enter a fresh token and save.
IssueLogs show reply status 400
The reply token expired or was already used. Send a fresh message and check the error on the next log line.
IssueTwo answers arrive for one message
Auto-reply messages is still enabled. Disable it inside LINE Official Account Manager.
Change the bot and redeploy#
Edit the answer function, run the test, and push. Then open the container page and click Rebuild. The new version must pass a health check before it takes requests.
node test.mjs
git commit -am "Update answers"
git pushWhen the latest entry on the Builds tab succeeds, message the bot to see the new answer.
If you deploy from an image, push a new tag and update the source, or turn on Auto-update on tag change when you create the container.
Turn it into a small JSON API#
The same structure works as an API for a website or app. Add this code above the line that answers not found.
if (req.method === 'GET' && pathname === '/api/hours') {
return send(res, 200, { open: '10:00', close: '20:00', timezone: 'Asia/Bangkok' });
}Push, click Rebuild, then call it.
curl https://SERVICE_URL/api/hoursFor an API only, remove the webhook part and the LINE variable check. Any API that changes data or exposes personal data must check who is calling first. This example is open for anyone to read.
Where to go next#
Extend your bot when you are ready
- Store files on the container
Add storage on the Volumes tab (limits the container to one instance, disables scale-to-zero, and bills continuously).
- Store customer data
Run a database on a VPS; see how to choose a size and secure it (the bot can still scale to 0; encrypt the connection).
- Connect automations
Forward jobs to
n8n on a VPS (n8n needs an always-on server).
- Avoid lost messages
Enable Webhook redelivery in
LINE (events may arrive twice; store
webhookEventIdand skip duplicates).- Use your shop's domain
Add it on the Domains tab and set DNS as shown on screen.
Still unsure which work suits which option? Read about daily and hourly server pricing and Container Apps.
Frequently asked questions#
Can I really run a
LINE bot for free?
Yes, as long as you stay within each container's monthly free quota. The example of 0.25 vCPU, 0.5 GiB, 150 hours and 300,000 requests fits inside it. Beyond that you pay, and LINE has its own separate message quota.
Why is the first message slow?
The service scaled to 0, so an instance has to start first. To keep one always ready, set Min replicas to 1, which bills vCPU and memory for as long as it runs.
Can I use
Python or Go instead of
Node.js?
Yes. The image must be linux/amd64 and serve HTTP on the Container port.
Do I have to check x-line-signature?
Yes. Anyone can call a webhook URL; the signature is what proves the data came from LINE unchanged. LINE does not publish the IP addresses it sends from, so IP filtering cannot replace it.
Can I use the bot with my shop's existing
LINE OA?
Yes. Enable the Messaging API on that account in LINE Official Account Manager, then turn off auto-replies that would answer on top of the bot.
Start with a bot that answers just three of the questions your shop gets most, then add one topic at a time.