แนวทางการเขียนโค้ดที่ปลอดภัยใน Node.js
ใช้แนวทางปฏิบัติที่ดีเพื่อป้องกันช่องโหว่ทั่วไป เช่น XSS, CSRF และการฉีดคำสั่ง SQL ในโค้ด Node.js
แนวทางการเขียนโค้ดที่ปลอดภัยใน Node.js เป็นบทเรียน Node.js Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Node.js Backend Development Bootcamp และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Node.js Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why Secure Coding Matters
Welcome! In this lesson, we'll dive into critical secure coding practices for Node.js. Writing secure code is just as important as writing functional code.
Understanding and preventing common vulnerabilities protects your application and your users from malicious attacks.
- Data Breaches: Exposed sensitive information.
- Service Downtime: Attacks can crash your application.
- Reputation Damage: Loss of user trust.

Cross-Site Scripting (XSS)
Cross-Site Scripting (XSS) is a common web vulnerability where attackers inject malicious scripts (usually JavaScript) into web pages viewed by other users.
When a user's browser loads the affected page, the malicious script executes, potentially stealing cookies, session tokens, or altering page content.
- Reflected XSS: Script immediately executed from user input.
- Stored XSS: Malicious script saved in database, then served to users.
- DOM-based XSS: Vulnerability in client-side code modifying the DOM.
Prevent XSS: Escape Output
The primary defense against XSS is to never trust user input and always escape it before rendering it to HTML.
This means converting characters like <, >, &, and " into their HTML entity equivalents (e.g., <, >). This way, the browser interprets them as text, not executable code.
Try running this example:
function escapeHtml(str) {
return str
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
const userInput = "<h1>Hello</h1><script>alert('XSS!');</script>";
const safeOutput = escapeHtml(userInput);
console.log("Original Input:\n", userInput);
console.log("\nEscaped Output (safe for HTML):\n", safeOutput);Prevent XSS: CSP
Beyond escaping, a Content Security Policy (CSP) adds another layer of defense against XSS.
CSP is an HTTP header that tells browsers which dynamic resources (scripts, styles, images) are allowed to load and from where. It can significantly mitigate the impact of XSS attacks by blocking unauthorized script execution.
Example header: Content-Security-Policy: default-src 'self'; script-src 'self' trusted.cdn.com;
SQL Injection Explained
SQL Injection (SQLi) is a web security vulnerability that allows an attacker to interfere with the queries an application makes to its database.
By injecting malicious SQL code into input fields, an attacker can trick the database into executing unintended commands, such as revealing sensitive data, modifying data, or even deleting tables.
A common example is altering a login query to bypass authentication without knowing the password.
Prevent SQLi: Parameterized Queries
The most effective way to prevent SQL Injection is by using parameterized queries (also known as prepared statements).
Instead of directly embedding user input into the SQL string, you use placeholders for values. The database then treats these placeholders as data, not as executable SQL code, preventing any malicious injection.
ORMs (Object-Relational Mappers) like Mongoose for MongoDB or Sequelize for SQL databases handle this automatically.
/*
This is a conceptual example for parameterized queries.
In a real app, you'd use a database driver or ORM (e.g., 'pg' for PostgreSQL).
*/
function executeSafeQuery(dbClient, userId) {
// Using a placeholder (?) ensures the input is treated as data, not code.
const query = "SELECT * FROM users WHERE id = ?";
console.log(`Executing SQL: "${query}" with param: "${userId}"`);
// In a real scenario, dbClient.query would execute this safely.
}
// Mock database client for demonstration purposes
const mockDbClient = {
query: (sql, params, callback) => {
// Simulate actual query execution logic here
console.log(" (Mock DB: Input handled safely)");
callback(null, [{ id: params, name: "John Doe" }]);
}
};
const maliciousUserId = "1 OR 1=1"; // This would be dangerous if not parameterized
const safeUserId = "1";
console.log("Attempting a 'malicious' ID (will be treated as a string value): ");
executeSafeQuery(mockDbClient, maliciousUserId);
console.log("\nAttempting a safe ID: ");
executeSafeQuery(mockDbClient, safeUserId);Cross-Site Request Forgery (CSRF)
Cross-Site Request Forgery (CSRF) is an attack that tricks a logged-in user into performing an unintended action on a web application.
Imagine you're logged into your bank. An attacker sends you a malicious link (e.g., in an email). If you click it, the attacker's site can make a request to your bank using your authenticated session, forcing you to transfer money without your knowledge.
The key is that the browser automatically sends your session cookies with the request to the bank's domain.
Prevent CSRF: CSRF Tokens
To prevent CSRF, we use CSRF tokens. A unique, unpredictable token is generated by the server for each user session and embedded in forms or headers.
When the user submits a request, the server verifies if the submitted token matches the one stored in the user's session. If they don't match, the request is rejected.
Since an attacker cannot know or forge this unique token for another user, they cannot trick the user into making a valid request.
/*
This is a conceptual example for CSRF token handling.
It is not runnable as a standalone script without a web server (e.g., Express).
*/
// 1. Server generates and stores a token in the user's session:
function generateCsrfToken() {
// In a real app, use a crypto-secure random string generator.
return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
}
const userSession = { id: "user123", csrfToken: null };
userSession.csrfToken = generateCsrfToken();
console.log("Server generated CSRF token for user:", userSession.csrfToken);
// 2. Server embeds this token in forms sent to the client:
const formHtml = `<form action="/transfer" method="POST">
<input type="hidden" name="_csrf" value="${userSession.csrfToken}">
<input type="number" name="amount">
<button type="submit">Transfer</button>
</form>`;
console.log("\nForm snippet with token (sent to client):\n", formHtml);
// 3. On submission, the server validates the token:
function validateCsrfToken(submittedToken, sessionToken) {
return submittedToken === sessionToken;
}
const userSubmittedToken = userSession.csrfToken; // Simulate valid submission
const attackerSubmittedToken = "fake_token_from_attacker";
console.log("\nValidation results:");
console.log(" Valid submission:", validateCsrfToken(userSubmittedToken, userSession.csrfToken));
console.log(" Attacker's submission:", validateCsrfToken(attackerSubmittedToken, userSession.csrfToken));Other Security Headers
Beyond the core vulnerabilities, several other HTTP security headers can enhance your Node.js application's security:
X-Content-Type-Options: nosniff: Prevents browsers from "sniffing" a response's content type, which can prevent XSS attacks.X-Frame-Options: DENY: Prevents your site from being embedded in an<iframe>, protecting against clickjacking attacks.Strict-Transport-Security (HSTS): Forces browsers to only connect to your site using HTTPS, preventing downgrade attacks.
These headers are typically set using middleware in frameworks like Express.js.
Security Vulnerability Check
Which of the following is the most effective defense against SQL Injection attacks?
Secure Coding Recap
Great job! You've learned about crucial secure coding practices in Node.js.
- XSS: Prevent by escaping all user-generated content before rendering to HTML, and use CSP.
- SQL Injection: Prevent by always using parameterized queries or ORMs.
- CSRF: Prevent by implementing CSRF tokens for state-changing requests.
- Remember to also use other security headers like
X-Content-Type-OptionsandX-Frame-Optionsfor a more robust defense.
Always assume user input is malicious and validate/sanitize/escape it appropriately!
เรียนรู้ JavaScript ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 22
- บทเรียน
- 92
คำถามที่พบบ่อย
บทเรียน “แนวทางการเขียนโค้ดที่ปลอดภัยใน Node.js” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “แนวทางการเขียนโค้ดที่ปลอดภัยใน Node.js” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Node.js Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Node.js Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “แนวทางการเขียนโค้ดที่ปลอดภัยใน Node.js”
ใช้แนวทางปฏิบัติที่ดีเพื่อป้องกันช่องโหว่ทั่วไป เช่น XSS, CSRF และการฉีดคำสั่ง SQL ในโค้ด Node.js คุณปฏิบัติ Node.js Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Node.js Backend Development Bootcamp หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Node.js Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “แนวทางการเขียนโค้ดที่ปลอดภัยใน Node.js” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Node.js Backend Development Bootcamp นี้ได้ไหม
ได้ บทเรียน Node.js Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- ทำความเข้าใจ OWASP Top 10
- แนวทางการเขียนโค้ดที่ปลอดภัยใน Node.js
- การเข้ารหัสและการทำแฮชข้อมูล
- การจำกัดอัตราและการป้องกันการเดาแบบลองทุกกรณี