// Import 'jsonwebtoken' module
const jwt = require('jsonwebtoken');
// Secret key for signing and verifying JWT tokens
const secret = 'mysecretkey';
// Create a JWT token with a payload and set expiration to 1 hour
const payload = { user_id: 123, username: 'john_doe' };
const token = jwt.sign(payload, secret, { expiresIn: '1h' });
// Verify a JWT token
try {
const decoded = jwt.verify(token, secret);
console.log(decoded);
} catch (error) {
console.error('Token verification failed.');
}JWT Token Creation and Verification in Node.js using 'jsonwebtoken'
Continue Reading
Discover more amazing content handpicked just for you
Build a Custom Rate Limiter in Node.js with Redis
// rateLimiter.js
const client = require("./redisClient");
const rateLimiter = (limit = 100, windowSec = 3600) => {
return async (req, res, next) => {
const ip = req.ip;
const key = `rate_limit:${ip}`;
const current = await client.get(key);
if (current !== null && parseInt(current) >= limit) {
return res.status(429).json({ error: "Too many requests. Try later." });
}
const multi = client.multi();
multi.incr(key);
if (!current) {
multi.expire(key, windowSec);
}
await multi.exec();
next();
};
};
module.exports = rateLimiter;// server.js
require("dotenv").config();
const express = require("express");
const rateLimiter = require("./rateLimiter");
const app = express();
const PORT = 3000;
app.use(rateLimiter(100, 3600)); // 100 requests/hour per IP
app.get("/", (req, res) => {
res.send("Welcome! You're within rate limit.");
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});Building a Real-Time Chat Application with WebSockets in Node.js
In this tutorial, we will create a real-time chat application using Node.js and WebSockets. Real-time communication is a crucial aspect of modern web applications, allowing users to interact with each other instantaneously. By leveraging WebSockets, we can establish a persistent connection between the client and server, enabling seamless data exchange.
WebSockets provide a full-duplex communication channel over a single TCP connection, allowing both the client and server to send messages at any time. Unlike HTTP, WebSockets maintain a persistent connection, making them ideal for applications requiring real-time updates, such as chat apps, online gaming, and live notifications.
Simple HTTP Server in Node.js
No preview available for this content.
Read and Write Files in Node.js using 'fs' module
No preview available for this content.
Simple RESTful API in Node.js using Express
No preview available for this content.
Date Manipulation and Sum Calculation
No preview available for this content.
Access Command-line Arguments
No preview available for this content.
Set and Access Environment Variable
No preview available for this content.
Event Emitter using 'events' module
No preview available for this content.
Construct File Path using 'path' module
// Import 'path' module
const path = require('path');
// Construct a file path using 'path.join'
const filePath = path.join(__dirname, 'files', 'example.txt');
// Log the generated file path
console.log('File Path:', filePath);Basic Authentication using 'express-basic-auth' middleware
No preview available for this content.
Hashing Password with SHA-256 using 'crypto' module
No preview available for this content.
Parse URL and Query Parameters
No preview available for this content.
Execute Shell Command using 'child_process' module
No preview available for this content.
File Stream Copy using 'fs' module
No preview available for this content.
Simple WebSocket Server using 'ws' library
No preview available for this content.
Discussion 0
Please sign in to join the discussion.
No comments yet. Start the discussion!