r/javascript • • Jan 24 '18

JavaScript best practices got 11k stars on Github

https://github.com/wearehive/project-guidelines
618 Upvotes

38 comments sorted by

16

u/vahidpg Jan 24 '18

Last year in order to achieve some consistency in setting up our javascript projects, we put together a set of best practices and asked the community to contribute. Thanks to your feedback (mostly on reddit) this documentation is in a much better state now. It has been translated in 3 languages, covers more aspects of a JS project and has achieved more than 11K stars on github. Our plan for the coming months is to add a section for GraphQL best practices as well as adding more translations.

7

u/badmonkey0001 Jan 24 '18

Don't use basic authentication unless over a secure connection (HTTPS)

In this day and age, nobody should be using basic HTTP auth. Nobody. Using your transport mechanism as your sole source of login security is a single point of failure. Remember that with basic auth the credentials (merely a base64 encoding) are re-sent with every request as well - far from ideal.

For further reading.

9

u/DoubleCandy Jan 24 '18

That is wrong. Basic auth is perfectly safe if used correctly (at least https and strong password). Basic auth is exactly like logging in to your reddit account, admin account on the api (where you can create tokens, add users etc..) or your super confidential customer database application. No where does it say that basic auth can't have IP restrictions, MFA, rate limiting, password rotation schedules, one time password etc.. Yes, I highly prefer (insist) to use oauth or other more sophisticated authentication schemes for actual integrations, but implying that it is not encrypted when we are sending it over https and that nobody should use it, ever, is just plain wrong. Yes it is not ideal, but no it is not inherently unsafe - if used correctly.

Authentication tokens must not be transmitted in the URL: GET /users/123?token=asdf....

Why:

Because Token, or user ID and password are passed over the network as clear text (it is base64 encoded, but base64 is a reversible encoding), the basic authentication scheme is not secure. > read more...

Another false claim there.. Query parameters are encrypted and irreversible if transmitted over https. Again, I agree that it is far from best practice (for instance because query parameters are logged literally everywhere, see owasp for more information), but stating obvious false facts as reasons for why something is considered bad practice is not the correct way of educating the community. When I see statements like that, it reduces my trust and confidence in the entire project, even though most of it is very very good and a great resource for the community.

Also stage-2 proposals?

0

u/badmonkey0001 Jan 24 '18

Tokens can be expired and do not leak passwords. The basic auth mechanism relies on the Authorization header being sent with every request, which is just a base64 encoding of user:pass. Sorry, but that's way too much password exposure to be reasonable by today's standards - https or no. A password exchange should only happen once and subsequent requests should be authenticated using a secondary mechanism that can expire.

7

u/DoubleCandy Jan 25 '18 edited Jan 25 '18

You are making way too many assumptions here. The only spec of basic auth is that is sent as "Basic base64(identifier:secret)" in the auth header. You are arguing about common implementations of basic auth vs tokens (e.g. "me" vs "on behalf of" authentication) - not the actual spec.

Tokens can be expired

How can password (secret) not be expired? I assume you are used to password rotations and expiring passwords..? You can easily make OTP for basic auth as well.. This is not really relevant in the discussion.

and do not leak passwords.

What is a token? It is a secret (password) that can be sent alone (without the user id - so it can be argued that a token is actually less secure than user:pass combination). What is the difference between leaking an api key/token vs leaking an identifier and a secret? You are assuming that tokens are made on behalf of the user and that basic auth is not. It is not unheard of having a userid with several tokens/secrets (just like your example of tokens, or even a unique identifier as well with the token/secret).

The basic auth mechanism relies on the Authorization header being sent with every request, which is just a base64 encoding of user:pass

I hope you require the Auth header on every request even if you use tokens..? Tokens are usually not even base64'ed so you are clearly missing the point. See next point.

A password exchange should only happen once and subsequent requests should be authenticated using a secondary mechanism that can expire.

And how do you propose to exchange username or password? Clearly not Basic auth I guess? Again you are assuming a "on behalf of" architecture here since you are "logging in" and then assuming another authentication mechanism because you need it to be expired. It will be just as secure to use basic auth to generate a OTP or short-lived password, token or secret to access a 3rd resource with your userid (or a tokenid to prevent leaking user information) in basic auth.

What about one-of-a-kind API calls made by a human? Do you propose to create your own authentication scheme (that is clearly not basic auth) to provide user:pass so I can generate a token that can expire in 1 hour so I can access the actual endpoint I needed to call this one time. What about Cathrine and Laura in HR that needs access to some data.. How do you teach them (or do you build a fully fledged application for this?) how to use your complicated authentication scheme on a locked down corporate network and make them use it instead of Cathrine asking Laura for her token (sent by email or written down etc) to save some time?

Point is, Basic auth in itself is not inherently insecure and depending on your use cases, it might as well be a good option. Of course, ideally you do not use root/master username/passwords in endpoints, only refresh and access tokens with very limited access and short expire time, a shared secret (or preferably public/private key) for signing the api requests with a nonce. Add in IP restrictions, rate-limiting, fingerprinting and tunnels etc as required. At some point the business case for increasing security through a more sophisticated authentication scheme is not worth it - this might already be at basic auth with a username/password for your local repair shop api that only responds their opening hours. We can't always have everything. Sometimes the question is no authentication or basic auth. God forbid you need to integrate some old system that only supports basic auth, but that is not a valid use case since no one ever should use basic auth I guess.

3

u/mlebkowski Jan 24 '18

Basic auth is perfectly valid as an additional level of authorization above your regular business logic. For example in test environments. You'd like to test your application from a point of an unaurhorized user, and yet not open it to the whole world.

1

u/badmonkey0001 Jan 24 '18

Want to use it in a controlled development environment that you don't care about being secure? Go for it. IMHO, you're better off developing against a more modern mechanism though.

1

u/mlebkowski Jan 25 '18

What kind of framework/technology lets you implement two distinct authorization methods at once? Another upside to the basic (or digest) auth is that it is very easy to add it on the load balancer/apache/nginx layer, so your app doesnt even know about it, so it doesnt add any differences between production and staging env.

1

u/[deleted] Jan 25 '18

That article is about using Basic Auth over HTTP. The advice here is that Basic Auth is fine iff you HTTPS.

1

u/zQpNB Jan 25 '18

I tried using it for actual browser UI auth (for fun i guess?) Browser's act all quirky about it. Can't even log out without doing weird stuff.

5

u/coderitual Jan 24 '18

Avoid URLs like this: GET /blogs/:blogId/posts/:postId/summary

For nested resources, use the relation between them in the URL. For instance, using id to relate an employee to a company. GET /schools/2/students/31

I assume it was created by different people but I spotted this after 3 mins of reading.

1

u/vahidpg Jan 24 '18

The first url is referring to a property rather than resource itself hence the suggestion to avoid it.

2

u/coderitual Jan 24 '18

I think you might be right. Still a bit confusing.

1

u/vahidpg Jan 25 '18 edited Jan 25 '18

After each bullet point there is ‘why’ section (it is quite hard to miss to be fair). On this one it says: “This is not pointing to a resource but to a property instead. You can pass the property as a parameter to trim your response.”

12

u/lucy_in_the_skyDrive Jan 24 '18

Yeah, but it's a little confusing to have two separate examples when you could have probably explained it better w/ the same one.

bad: /blogs/:blogId/posts/:postId/summary

good: /blogs/:blogId/posts/:postId

Then get summary off of the Post response object instead of building a strange query to get one property.

42

u/crazyfreak316 Jan 24 '18

For the record, these are not "Javascript best practices" but Javascript project best practices. The difference is important.

3

u/flipperdeflip Jan 25 '18

Most of these are not even specifically Javascript related.

30

u/[deleted] Jan 24 '18

Organize your files around product features / pages / components, not roles. Also, place your test files next to their implementation.

Thank. You.

Even a tightly scoped project can get downright unreadable if you're dumping everything into a components folder.

3

u/[deleted] Jan 24 '18

12k now

3

u/sylvanaar Jan 25 '18

I disagree with history rewriting. It is a bad practice.

2

u/Kingsizepeanut Jan 24 '18

Thanks, this is something I've been looking for for ages! Seems to be well formatted and concise.

Thanks for posting!

1

u/KinkyCode Jan 24 '18

Those are rookie numbers, you gotta bring those numbers up.

-23

u/faded_filth Jan 24 '18

Stars, upvotes, downvotes ... what is this obsession? Meaningless. They are literally just clicks of a button made by users, bots and trolls.

1

u/LogicMirror Jan 25 '18

Your comment ... what is this obsession? Meaningless. It's literally typing of letters by someone who can only see in black & white.

-11

u/faded_filth Jan 24 '18

gets 17 downvotes in 6 hours

aww you peopleHHHHH trendy javascript developers make me feel special _^

1

u/flipperdeflip Jan 25 '18

WALK IN LINE! OBEY!

0

u/[deleted] Jan 24 '18

[deleted]

16

u/dedben Jan 24 '18

it still recommends using "stage-2 features"...

TL;DR on why this is bad for JS newbies like me?

23

u/adbachman Jan 24 '18

Stage-2 is mostly stable but still draft / incomplete. They are features that are likely to be included in the next JS specification, but they’re not final.

Just means you might be learning something that’s going to change in 6 months, but what else is new?

The description over at Babel.js has more detail about what it actually includes: https://babeljs.io/docs/plugins/preset-stage-2/

0

u/[deleted] Jan 24 '18

[deleted]

8

u/Mingli91 Jan 24 '18

Stage 2 is generally the place that many people start using new features since at that stage of the TC39 process the syntax is covered but more importantly the APIs have already been decided, so if the internals change then it makes no difference.

With Babel, you run no risk whatsoever putting this in production code. Many of the big players use stage 2 as their starting point. Facebook is a good example - you can see evidence of it in their OSS projects (check out React Native, which includes stage 2 features by default).

Worst comes to worst and the spec changes, the Babel plugin or polyfill isn't going anywhere, and you have the simple task of removing the new features from your code.

Full stage 2 description:

Draft: all major semantics, syntax and API are covered, but TODOs, placeholders and editorial issues are expected

Obviously it's up to the individual or the company, but the only risk is losing a couple of hours if the spec does change dramatically.

0

u/Tomseph Jan 25 '18

Stage 2 means "We're close to final draft" but it doesn't mean that it will become an accepted feature. Stage 3+ is the only assurance that the feature will become part of the Javascript. Object.observe was at Stage 2 before it was withdrawn.

3

u/pm_me_ur__labia Jan 24 '18

Have you tried making a pull request?

-6

u/kor0na Jan 24 '18

You realize everyone transpiles their code anyway, right?

6

u/[deleted] Jan 24 '18

Yeah, that's bad advice by default.

I disagree with those who wouldn't use ESNext features in production projects, but equally I don't think you should be chucking an entire stage preset into your project.

Use stable by default, and then add in individual features as plugins as needed (for example https://github.com/OpenSourceCTF/website/blob/develop/.babelrc.js#L33).

1

u/cogman10 Jan 24 '18

I mean, the feature should bring a lot before you deviate from stable. Because every unstable feature you add is a potential hitch that will prevent you from using new features and newer transpilers. Something that really should be avoided if possible.

3

u/[deleted] Jan 25 '18

I agree. For me object spread is always worth it, for example, as it's a lot nicer to work with than Object.assign.

4

u/[deleted] Jan 24 '18

And after all this time, and comments on reddit

you'll still find some trivial shit to nitpick...

1

u/madwill Jan 24 '18 edited Jan 24 '18

I'm quite lazy, could you say which ones ?

edit: Oh nevermind, it straight up recommend to use stage2.

Anybody had an actual problem using stage 2 things at some point where their use case was broken by a change in specifications ?

I mean i use decorators, absolutif love them, a lot more than HoC in react. I use an old converter for them, i have no know problem and don't expect any if it updates its implementation.