Keywords: Node.js | HTTP Server | Cookie Handling
Abstract: This article provides an in-depth exploration of implementing single cookie reading and setting functionality in Node.js native HTTP server without relying on third-party libraries. Through parsing the Cookie header in HTTP requests and setting the Set-Cookie header in responses, it offers complete code implementation and detailed technical analysis, including cookie parsing algorithms, encoding handling, and security considerations, helping developers deeply understand the underlying implementation of HTTP cookie mechanisms in Node.js.
Introduction
In web development, cookies are essential mechanisms for session management and state persistence. Node.js, as a popular server-side JavaScript runtime, provides basic web server functionality through its native HTTP module but does not directly encapsulate cookie operation interfaces. Based on high-scoring answers from Stack Overflow, this article deeply analyzes how to implement single cookie reading and setting in Node.js HTTP server while avoiding third-party dependencies.
Fundamental Principles of Cookies
HTTP cookies are small pieces of data sent from the server to the user's browser and stored locally. The browser automatically carries this data in subsequent requests. Cookies are transmitted through HTTP header fields: servers set cookies via the Set-Cookie response header, while clients send cookies via the Cookie request header.
Implementing Cookie Parsing Functionality
Since Node.js native HTTP module does not provide cookie parsing functionality, manual implementation of parsing logic is required. Below is the complete cookie parsing function:
function parseCookies(request) {
const list = {};
const cookieHeader = request.headers?.cookie;
if (!cookieHeader) return list;
cookieHeader.split(`;`).forEach(function(cookie) {
let [name, ...rest] = cookie.split(`=`);
name = name?.trim();
if (!name) return;
const value = rest.join(`=`).trim();
if (!value) return;
list[name] = decodeURIComponent(value);
});
return list;
}This function first checks if the Cookie field exists in the request headers, returning an empty object if absent. It then splits the cookie string by semicolons, splits each cookie by equals sign into name and value, and performs necessary trimming and URL decoding. This implementation properly handles cookie values containing special characters.
Complete Server Implementation
Combining the cookie parsing functionality, a complete HTTP server can be constructed:
const http = require('http');
const server = http.createServer(function(request, response) {
// Read cookies
const cookies = parseCookies(request);
// Set cookie
response.writeHead(200, {
"Set-Cookie": `mycookie=test`,
"Content-Type": `text/plain`
});
response.end(`Hello World\n`);
}).listen(8124);
const {address, port} = server.address();
console.log(`Server running at http://${address}:${port}`);In this implementation, each request reads cookies sent by the client and sets a cookie named mycookie with value test. The server listens on port 8124 and returns a simple text response.
Technical Detail Analysis
The cookie parsing algorithm must handle various edge cases: cookie values may contain equals signs, so simple split('=') cannot be used once; cookie names and values may have leading/trailing spaces; cookie values may be URL encoded. The above implementation handles equals signs in cookie values through rest.join(`=`), removes whitespace with trim(), and performs URL decoding via decodeURIComponent().
When setting cookies, directly manipulating the Set-Cookie response header is the most straightforward approach. Cookie attributes can be further extended, such as expiration time, domain, path, etc.:
response.writeHead(200, {
"Set-Cookie": `mycookie=test; Max-Age=3600; Path=/; HttpOnly`,
"Content-Type": `text/plain`
});Comparison with Express Framework
While the Express framework provides more concise cookie operation interfaces like res.cookie() and req.cookies, understanding the native implementation helps deeply grasp HTTP protocol details. The native implementation avoids framework dependencies, making it more suitable for learning and small projects.
Security Considerations
In practical applications, cookie security must be considered: use the HttpOnly flag to prevent XSS attacks, use the Secure flag to ensure HTTPS transmission, and set appropriate expiration times to avoid session hijacking. These can all be implemented by extending the Set-Cookie header.
Conclusion
By manually parsing the Cookie request header and setting the Set-Cookie response header, complete cookie read and write functionality can be implemented in Node.js native HTTP server. Although this approach requires slightly more code, it provides deep understanding of the HTTP protocol and avoids unnecessary dependencies. Developers can extend this basic implementation based on specific needs to add more complex cookie management features.