AI 资讯
Environment Variables in Node.js: The Complete Guide (2026)
Environment Variables in Node.js: The Complete Guide (2026) Environment variables are the standard way to configure apps across environments. Here's how to use them correctly. What and Why What: Key-value pairs set outside your application code Where: OS environment, .env files, CI/CD config, container orchestration Why: → Separate config from code (12-Factor App methodology) → Same code runs everywhere (dev, staging, production) → Secrets never committed to git → Easy to change behavior without redeploying Reading Env Vars in Node.js // Method 1: process.env (built-in, always available) const port = process . env . PORT || 3000 ; const dbUrl = process . env . DATABASE_URL ; const apiKey = process . env . API_KEY ; // ⚠️ process.env values are ALWAYS strings! const timeout = parseInt ( process . env . TIMEOUT , 10 ) || 5000 ; const debug = process . env . DEBUG === ' true ' ; const maxRetries = Number ( process . env . MAX_RETRIES || ' 3 ' ); // Method 2: dotenv (most popular approach) // npm install dotenv import ' dotenv/config ' ; // Loads .env into process.env automatically // Now process.env has all your .env variables! // Or explicit load: import dotenv from ' dotenv ' ; dotenv . config ({ path : ' .env.local ' }); // Custom file path // Method 3: env-cmd (for package.json scripts) // "dev": "env-cmd -f .env.dev node server.js" // "prod": "env-cmd -f .env.prod node server.js" // Method 4: tenv / enve (type-safe alternatives) import { env } from ' tenv ' ; const port = env . number ( ' PORT ' , 3000 ); // Type-safe with default const dbUrl = env . string ( ' DATABASE_URL ' ); // Required, throws if missing const debug = env . bool ( ' DEBUG ' , false ); // Boolean parsing The .env File Ecosystem # .env (committed to git with defaults) NODE_ENV = development PORT = 3000 LOG_LEVEL = debug # .env.local (NOT committed! Gitignored) # Contains local overrides and secrets DATABASE_URL = postgresql://localhost/myapp_dev API_KEY = sk_test_local_key JWT_SECRET = local-de
AI 资讯
We Replaced Jest With node:test in 12 Services — Here's What Broke and What Didn't
After months of using Jest for unit testing, we decided to take the plunge and migrate to the built-in node:test runner. The results were surprising, with some features working seamlessly and others requiring significant rework. In this post, we'll share our journey and the lessons we learned along the way. Introduction to node:test The node:test runner is a built-in testing framework that comes with Node.js. It's designed to be fast, efficient, and easy to use. Here's an example of a simple test using node:test: import { test } from ' node:test ' ; import { Command } from ' @aws-sdk/client-lambda ' ; test ( ' Lambda client test ' , async ( t ) => { const lambdaClient = new Command (); const response = await lambdaClient (); t . equal . responseStatusCode , 200 ; }); Warning: When using node:test, make sure to handle errors properly, as unhandled errors can cause the test runner to crash. Migrating from Jest to node:test Migrating from Jest to node:test requires some changes to your test code. One of the main differences is the way you handle ES modules. In Jest, you can use the jest.config.js file to configure how ES modules are handled. In node:test, you need to use the --test-type option to specify the type of test you're running. Here's an example of how to migrate a Jest test to node:test: // jest.test.js import { lambdaClient } from ' ../lambdaClient ' ; describe ( ' Lambda client test ' , () => { it ( ' should return 200 ' , async () => { const response = await lambdaClient (); expect ( response . statusCode ). toBe ( 200 ); }); }); // node-test.test.js import { test } from ' node:test ' ; import { lambdaClient } from ' ../lambdaClient ' ; test ( ' Lambda client test ' , async ( t ) => { const response = await lambdaClient (); t . equal ( response . statusCode , 200 ); }); Tip: Use the --coverage option to generate code coverage reports for your tests. Overcoming Incompatibilities and Limitations One of the main limitations of node:test is that it does not su
AI 资讯
Why I built tmpdrop: a self-hosted, expiring file drop
I had a screenshot to send. Nothing secret — a stack trace from a side project — but it had an internal hostname, a file path with my username, and a chunk of a config file in the terminal behind it. The fast move is to drag it onto a free image host and paste the link. I sat there with my cursor over the upload button and couldn't do it. Because I know what happens next. That image lives on someone else's infrastructure, indefinitely, behind a URL I don't control, and I have no idea who else can reach it. For a throwaway screenshot, that's a permanent record I never agreed to. So I closed the tab and built a thing instead. It's called tmpdrop , and it's ~500 lines of Node. The threat model The problem with public file hosts isn't that they're evil. It's the gap between what you intend ("share this once, with one person") and what the platform delivers ("store this forever, serve it to anyone who finds the link"). A few specific things go wrong: Retention. "Temporary" hosts keep your files long after you've forgotten them. There's no expiry you can trust, and deletion is usually best-effort. Predictable URLs. Plenty of hosts use sequential or short IDs. Scrapers walk the keyspace and hoover up everything. Your "private" link was never private. Stored XSS via uploads. If a host serves an uploaded .html or .svg file inline with a permissive content type, an attacker can ship JavaScript that runs in your browser, in the host's origin. Your file host becomes an XSS delivery service. Abuse vectors. No rate limit means the box is a free CDN for whatever someone wants to dump on it — malware, spam payloads, the works. So the design goal wasn't "another uploader." It was: close each of those gaps, then stop. What I built tmpdrop is a single Fastify server backed by SQLite. The whole defensive surface is small enough to hold in your head: Unguessable URLs. Slugs are 9 random bytes, base64url-encoded — 72 bits of entropy. You cannot enumerate them. A TTL reaper. Every upload
AI 资讯
How I scraped the CQC Care Register without hitting the API auth wall
The Care Quality Commission regulates 56,000+ healthcare and social care locations in England — care homes, GP surgeries, hospitals, dental practices, home care agencies. If you work in care sector tech, you've probably needed this data at some point. There's a CQC REST API, and I was planning to wrap it. Then I hit the auth wall. The API is now authenticated CQC migrated their API to api.service.cqc.org.uk and added bearer token authentication. You need to register at their developer portal, create an application, and include an Authorization: Bearer <token> header on every request. That's not a dealbreaker for enterprise use cases, but it creates friction for a data product — it means requiring users to register with CQC before they can run your actor. I checked the old API base ( api.cqc.org.uk/public/v1 ) as a fallback. HTTP 403. Fully blocked. The open-data file rescue CQC publishes a monthly open-data file called HSCA_Active_Locations.ods . It's a 23 MB OpenDocument Spreadsheet with every active regulated location in England — all 56,000 of them. Free, no auth, Open Government Licence. The URL is date-stamped and changes each month, but the transparency page always links to the current version. The approach: scrape the transparency page to find the current ODS URL, download the file, parse it, filter rows, push results. No API. No auth wall. The ODS parsing challenge ODS files ( .ods ) are ZIP archives containing XML. The standard tool for parsing them in Node.js is SheetJS ( xlsx package, v0.18.5 — the last Apache 2.0 release). The first surprise: the workbook has three sheets — README , HSCA_Active_Locations , and Dual_Registration_Locations . SheetJS defaults to the first sheet, which is the README with 34 rows. I added logic to find the sheet with the most rows. for ( const name of workbook . SheetNames ) { const probe = XLSX . utils . sheet_to_json ( sheet , { header : 1 }); if ( probe . length > bestCount ) { bestCount = probe . length ; bestSheet = shee