copypasta allows bugs (and more) to creep into production code

I’m writing an Express app. I care about infosec. Naturally I went a-Googling to learn methods to harden Express apps. At some point I came across micaksica’s article, Your Node.js authentication tutorial is (probably) wrong.

The gold nugget quote comes right in the opening paragraph,

Thousands of front-end developers being thrown into the server-side JS maelstrom are trying to piece together actionable knowledge from these tutorials, either by cargo-cult-copypasta or gratuitous use of npm install as they scramble frantically to meet the deadlines set for them by outsourcing managers or ad agency creative directors.

Would you like some crippling performance issues to go with your copypasta? My next step found an illustrative example.

Getting conceptual: blocking versus non-blocking code

The Node documentation already gives a rundown on the differences between code that is blocking versus code that is non-blocking.

tl;dr it would be silly for the rest of your app to have to wait while asynchronous functions are happening, so it doesn’t. That’s what we mean when we say that async functions are non-blocking; we don’t block the rest of the app from doing its thing when they’re invoked.

Hashing passwords

One key piece of advice from micaksica’s article is to hash passwords using bcrypt. It’s such commonly given advice that it’s reached meme status.

Check out this code sample for hashing passwords in Node:

First usage example uses synchronous call to bcrypt compare

It’s the first usage example from the docs for bcrypt-nodejs, ie the first thing some naïve developer is likely to copy&paste into their app after Googling ‘node js bcrypt’.

If you know bcrypt as an algorithm you know that it’s kind of famous for being two things: good, and slooow.

Now imagine an app that blocks execution every single time it hashes or checks a password using this slooow encryption algorithm, because it’s using the sync version of those functions.

Bad bad not good fam.

The npm package bcrypt is friendlier to copypasta developers, giving the async usage example first, tagging it recommended, and eventually explaining why it is the recommended function to use.

What does this mean for copypasta developers

Don’t believe everything you read on the Internet. I definitely won’t be the one to tell you not to copy code snippets into your projects. Everybody does it. Just don’t copy code snippets that you don’t fully understand into your projects.

What does this mean for package maintainers, tutorial writers, et al

Like micaksica, I acknowledge copypasta coding as a common practice, and one that can lead to poor practices creeping into production apps. Writing documentation mindful of this fact is one thing we can do to improve the overall JavaScript development ecosystem.