Securing Netlify Webhooks on a Home Server with HMAC and Timestamps
I am Kaleb, a web developer at Dream Futures Tech in Pompano Beach, Florida. At my office and on my home automation server, I rely heavily on webhooks to pass data between static frontends hosted on Netlify and local ser
I am Kaleb, a web developer at Dream Futures Tech in Pompano Beach, Florida. At my office and on my home automation server, I rely heavily on webhooks to pass data between static frontends hosted on Netlify and local services running behind my router. When you expose an endpoint to the public internet to receive serverless triggers, security matters immediately.
A static secret token passed in a custom header is a common starting point. If someone discovers your URL, they cannot trigger your automation without the token. However, a static token leaves you vulnerable to replay attacks. If an intermediate network node or a malicious actor captures a legitimate webhook payload and its header, they can replay that exact HTTP request indefinitely.
To solve this, I added request signing using HMAC-SHA256 paired with a strict timestamp check. This pattern ensures two things: the payload has not been tampered with, and the request was generated within a very short execution window.
The Design Pattern
When my Netlify function dispatches a webhook to my home server, it attaches three custom headers:
-
x-signature: The hexadecimal HMAC-SHA256 hash of the timestamp and the request body, calculated using a shared secret. -
x-timestamp: The Unix epoch timestamp of when the request was generated. -
content-type: Standard application/json.
When the home server receives this request, it performs three validation steps before processing the payload. It checks if the timestamp is missing, it verifies that the timestamp is within a five-minute window to prevent replays, and it recalculates the HMAC locally using the shared secret and compares it to the incoming signature using a timing-safe function.
Sending the Signed Request from Netlify
In my Netlify serverless functions, I use the native Node.js crypto module to construct the signature. Here is the implementation shape I use in production.
const crypto = require('crypto');
exports.handler = async function(event) {
if (event.httpMethod !== 'POST') {
return { statusCode: 405, body: 'Method Not Allowed' };
}
const secret = process.env.WEBHOOK_SECRET;
const timestamp = Math.floor(Date.now() / 1000).toString();
const body = event.body;
// 1. Create the payload string by combining timestamp and body
const signedPayload = `${timestamp}.${body}`;
// 2. Generate the HMAC-SHA256 signature
const signature = crypto
.createHmac('sha256', secret)
.update(signedPayload)
.digest('hex');
// 3. Dispatch the request to the home server endpoint
try {
const response = await fetch(process.env.HOME_SERVER_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-signature': signature,
'x-timestamp': timestamp
},
body: body
});
if (!response.ok) {
throw new Error('Home server rejected webhook');
}
return { statusCode: 200, body: JSON.stringify({ success: true }) };
} catch (error) {
return { statusCode: 500, body: JSON.stringify({ error: error.message }) };
}
};
Combining the timestamp directly into the string that gets hashed prevents an attacker from altering the timestamp header independently of the body. If they change the timestamp, the hash breaks. If they change the body, the hash breaks.
Verifying on the Home Server
On my Express-based home automation server, I use raw body parsing middleware to ensure the signature is calculated against the exact byte stream sent by Netlify. Parsing JSON prematurely can alter whitespace or key ordering, which causes signature verification to fail.
const express = require('express');
const crypto = require('crypto');
const app = express();
// Capture raw body for signature verification
app.use(express.json({
verify: (req, res, buf) => {
req.rawBody = buf;
}
}));
app.post('/webhook', (req, res) => {
const signature = req.headers['x-signature'];
const timestamp = req.headers['x-timestamp'];
const secret = process.env.WEBHOOK_SECRET;
if (!signature || !timestamp) {
return res.status(401).send('Missing security headers');
}
// 1. Check timestamp drift (5 minutes maximum tolerance)
const currentTime = Math.floor(Date.now() / 1000);
const requestTime = parseInt(timestamp, 10);
const toleranceWindow = 300;
if (isNaN(requestTime) || Math.abs(currentTime - requestTime) > toleranceWindow) {
return res.status(401).send('Timestamp outside acceptable window');
}
// 2. Recreate the signed payload string
const signedPayload = `${timestamp}.${req.rawBody}`;
// 3. Compute expected signature
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(signedPayload)
.digest('hex');
// 4. Use timing-safe comparison to prevent timing attacks
const sigBuffer = Buffer.from(signature, 'hex');
const expectedBuffer = Buffer.from(expectedSignature, 'hex');
if (sigBuffer.length !== expectedBuffer.length || !crypto.timingSafeEqual(sigBuffer, expectedBuffer)) {
return res.status(401).send('Invalid signature');
}
// Processing valid payload
console.log('Verified webhook received:', req.body);
res.status(200).send('Received');
});
app.listen(3000);
Architectural Judgment
In my view, implementing HMAC signing with timestamps directly is preferable to pulling in heavy third-party webhook verification libraries for simple custom setups. The entire logic fits into a few lines of standard library code. Using crypto.timingSafeEqual is critical here; standard string comparisons can leak information through execution time discrepancies.
By enforcing a five-minute tolerance window, clock drift between Netlify execution nodes and my local home hardware is absorbed cleanly, while still rendering captured payloads useless shortly after transmission. This approach keeps infrastructure overhead low and maintains high operational confidence.
I build sites and automations for small businesses at dreamfuturestech.com.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.