Verify Railway webhooks
Railway doesn't sign webhooks, so there's no signature to check and no SDK to verify one. Its docs say to add a custom header with a secret value, such as Authorization: Bearer <token> or X-Webhook-Secret, and reject any request without it. That authenticates the sender, but it doesn't protect the body or stop a replay, and the timestamp in the body isn't signed.
These pages cover the events Railway sends about your project. To receive other services' webhooks in an app you host on Railway, see how to receive and replay external webhooks in Railway.
The facts
Railway webhook secret
Railway doesn't issue a secret. You choose a header name and value on the webhook, and Railway sends them with every delivery and with Test Webhook. Keep it in an environment variable, not in source code.
- Add headers in the Custom headers section of the webhook form, one name and one value per row, up to 20 per webhook.
- Values are stored encrypted and never shown again. After you save, a row shows
Unchanged, so keep your own copy. - To rotate, type a new value over
Unchangedand update your endpoint at the same time. Leaving the field empty keeps the stored value. - Names can be up to 128 characters of letters, digits,
-and_. Values can be up to 4096 characters with no line breaks. - Railway refuses
Host,Content-Type,Content-Length, the hop-by-hop headers, and names starting withProxy-orX-Railway-.
Source: Railway docs ↗
Code
// Generated with: railway-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config({ quiet: true });
const crypto = require('crypto');
const express = require('express');
const app = express();
/**
* Constant-time string comparison. Hashing both sides first gives equal-length
* buffers, so timingSafeEqual never throws and the secret's length isn't leaked.
*/
function safeEqual(a, b) {
const ha = crypto.createHash('sha256').update(String(a)).digest();
const hb = crypto.createHash('sha256').update(String(b)).digest();
return crypto.timingSafeEqual(ha, hb);
}
/**
* Railway does not sign payloads. You add a custom header (name and value) to the
* webhook in Project Settings > Webhooks; Railway sends it with every delivery.
* The header name is yours, so it comes from RAILWAY_WEBHOOK_HEADER, and the WHOLE
* expected value (including any "Bearer " prefix) from RAILWAY_WEBHOOK_SECRET.
* Node lowercases incoming header names, so the lookup is case-insensitive.
*/
function verifyRailwayRequest(
headers,
secret = process.env.RAILWAY_WEBHOOK_SECRET,
headerName = process.env.RAILWAY_WEBHOOK_HEADER || 'Authorization'
) {
if (!secret) return false; // never accept when unconfigured
const received = headers[headerName.toLowerCase()];
return typeof received === 'string' && received !== '' && safeEqual(received, secret);
}
function handleEvent(payload) {
const { type, details, resource } = payload;
const service = resource && resource.service && resource.service.name;
switch (type) {
case 'Deployment.failed':
console.log(`Deployment failed${service ? ` for ${service}` : ''}: ${details && details.id}`);
// Your code: alert the team (details.commitMessage, resource.project, resource.environment)
break;
default:
// Other deployment states (Deployment.<state>) and alert types are not enumerated in
// Railway's docs, so match on the prefix and log anything else.
if (typeof type === 'string' && type.startsWith('Deployment.')) {
console.log(`Deployment ${type.slice('Deployment.'.length)}${service ? ` for ${service}` : ''}`);
// Your code: update your deploy dashboard
} else {
console.log(`Unhandled event: ${type}`);
}
}
}
// Read the body raw (any content type) so the request is authenticated before parsing.
app.post('/webhooks/railway', express.raw({ type: '*/*' }), (req, res) => {
if (!verifyRailwayRequest(req.headers)) {
return res.status(401).json({ error: 'Invalid or missing webhook secret header' });
}
let payload;
try {
const raw = Buffer.isBuffer(req.body) ? req.body.toString('utf8') : '';
payload = JSON.parse(raw);
} catch {
return res.status(400).json({ error: 'Invalid JSON body' });
}
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
return res.status(400).json({ error: 'Expected a JSON object' });
}
try {
handleEvent(payload);
} catch (err) {
console.error('Error handling Railway event:', err);
return res.status(500).json({ error: 'Handler error' });
}
res.status(200).json({ received: true });
});
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
module.exports = app;
module.exports.verifyRailwayRequest = verifyRailwayRequest;
if (require.main === module) {
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log(`Webhook endpoint: POST http://localhost:${PORT}/webhooks/railway`);
});
} // Generated with: railway-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { verifyRailwayRequest } from '../../../lib/verify-railway';
interface RailwayPayload {
type?: string;
details?: { id?: string; [key: string]: unknown };
resource?: { service?: { name?: string }; [key: string]: unknown };
[key: string]: unknown;
}
function handleEvent(payload: RailwayPayload): void {
const { type, details, resource } = payload;
const service = resource?.service?.name;
switch (type) {
case 'Deployment.failed':
console.log(`Deployment failed${service ? ` for ${service}` : ''}: ${details?.id}`);
// Your code: alert the team (details.commitMessage, resource.project, resource.environment)
break;
default:
// Other deployment states (Deployment.<state>) and alert types are not enumerated in
// Railway's docs, so match on the prefix and log anything else.
if (typeof type === 'string' && type.startsWith('Deployment.')) {
console.log(`Deployment ${type.slice('Deployment.'.length)}${service ? ` for ${service}` : ''}`);
// Your code: update your deploy dashboard
} else {
console.log(`Unhandled event: ${type}`);
}
}
}
export async function POST(request: NextRequest) {
// Authenticate before reading or parsing the body.
if (!verifyRailwayRequest(request.headers)) {
return NextResponse.json({ error: 'Invalid or missing webhook secret header' }, { status: 401 });
}
let payload: unknown;
try {
// Read as text so any content type is accepted.
payload = JSON.parse(await request.text());
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
}
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
return NextResponse.json({ error: 'Expected a JSON object' }, { status: 400 });
}
try {
handleEvent(payload as RailwayPayload);
} catch (err) {
console.error('Error handling Railway event:', err);
return NextResponse.json({ error: 'Handler error' }, { status: 500 });
}
return NextResponse.json({ received: true });
} # Generated with: railway-webhooks skill
# https://github.com/hookdeck/webhook-skills
import hashlib
import hmac
import json
import os
from dotenv import load_dotenv
from fastapi import Depends, FastAPI, HTTPException, Request
load_dotenv()
app = FastAPI()
def safe_equal(a: str, b: str) -> bool:
"""Constant-time comparison. Both sides are encoded to bytes (compare_digest raises on
non-ASCII str) and hashed so the digests have equal length."""
return hmac.compare_digest(
hashlib.sha256(a.encode("utf-8")).digest(),
hashlib.sha256(b.encode("utf-8")).digest(),
)
def verify_railway_request(headers, secret=None, header_name=None) -> bool:
"""Railway does not sign payloads. You add a custom header (name and value) to the
webhook in Project Settings > Webhooks; Railway sends it with every delivery.
The header name comes from RAILWAY_WEBHOOK_HEADER (default Authorization) and the WHOLE
expected value (including any "Bearer " prefix) from RAILWAY_WEBHOOK_SECRET.
Starlette headers are case-insensitive.
"""
secret = secret if secret is not None else os.environ.get("RAILWAY_WEBHOOK_SECRET")
header_name = header_name or os.environ.get("RAILWAY_WEBHOOK_HEADER") or "Authorization"
if not secret:
return False # never accept when unconfigured
received = headers.get(header_name)
return bool(received) and safe_equal(received, secret)
async def require_railway_secret(request: Request) -> None:
"""FastAPI dependency: reject the request before the body is parsed."""
if not verify_railway_request(request.headers):
raise HTTPException(status_code=401, detail="Invalid or missing webhook secret header")
def handle_event(payload: dict) -> None:
event_type = payload.get("type")
details = payload.get("details") or {}
service = ((payload.get("resource") or {}).get("service") or {}).get("name")
suffix = f" for {service}" if service else ""
if event_type == "Deployment.failed":
print(f"Deployment failed{suffix}: {details.get('id')}")
# Your code: alert the team (details["commitMessage"], payload["resource"])
# Other deployment states (Deployment.<state>) and alert types are not enumerated in
# Railway's docs, so match on the prefix and log anything else.
elif isinstance(event_type, str) and event_type.startswith("Deployment."):
print(f"Deployment {event_type[len('Deployment.'):]}{suffix}")
# Your code: update your deploy dashboard
else:
print(f"Unhandled event: {event_type}")
@app.post("/webhooks/railway", dependencies=[Depends(require_railway_secret)])
async def railway_webhook(request: Request):
# Read the raw body so any content type is accepted.
raw_body = await request.body()
try:
payload = json.loads(raw_body)
except (json.JSONDecodeError, UnicodeDecodeError):
raise HTTPException(status_code=400, detail="Invalid JSON body")
if not isinstance(payload, dict):
raise HTTPException(status_code=400, detail="Expected a JSON object")
try:
handle_event(payload)
except Exception as err: # noqa: BLE001
print(f"Error handling Railway event: {err}")
raise HTTPException(status_code=500, detail="Handler error")
return {"received": True}
@app.get("/health")
async def health():
return {"status": "ok"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000) Or install the Railway webhooks skill:
npx skills add hookdeck/webhook-skills --skill railway-webhooks
Common failures
Prefix left out of the comparison
Compare the whole header value. If you typed Bearer abc as the value, the value to compare is Bearer abc, not abc.
Header name mismatch
You choose the name when you add the header. Your endpoint has to read the same name, and header names are case-insensitive.
Saved value out of step
After you save, Railway shows Unchanged and never shows the value again. If your copy is lost or stale, type a new value in Railway and update your endpoint at the same time.
Let Event Gateway check your Railway header.
Event Gateway compares the header you name with the exact value you enter on each Railway request, and a request that doesn't match never reaches your service. It queues the rest and retries failures on your schedule.