Node - Js Best Practices and Security
Node - Js Best Practices and Security
● Over the last couple of years, Node.js has been one of the most popular
platforms.
● It is definitely easy to get started on those Node.js projects, but
understanding how to better organise your code and how to deal with errors
can often become a nightmare once you get past the simple Hello World
app (as with most languages and frameworks).
● When designing applications for production, it is a must to adopt the best
practises in Node.js programming, whether you are a novice or a seasoned
developer using Node.
Managing Project Structure
● Npm init will automatically generate a package.json file for your project that
shows all the packages/node applications of npm install has the
information of your project.
Wrap Common Utilities as npm Package
● We should preserve our app-level keys readable from file and environment
variables as security best practises.
● For easier usability, we can also keep secrets outside the committed code
and make a configuration file hierarchy.
● A complete and flawless configuration setup is needed to meet all this.
● In their projects, developers can also leverage the power of npmrc file, which
during npm init can automate quite a few environment configurations, such
as setting up metadata within the project package
Avoiding Garbage in-app
● Node js has a 1.5 GB default limit, but a selfish and lazy garbage collector is
still used.
● It waits until it uses the whole memory and recovers on its own.
● We can set the flags on the V8 if you want to gain more power over the
garbage collector.
● If the app is running in an environment with less than 1.5 GB of usable
memory, this is significant.
Hook Things Up
● For automation, we can make perfect hooks using Npm's lifecycle scripts.
● We can use a pre-install script if we want to run something before building
our app.
● You can build assets with a grunt, gulp and browser or webpack of the
production application using a post-install script in the JSON package.
Error Handling of the App
● To ensure that the request body is proper and does not contain any
malicious material, developers may use available open-source packages like
Joi.
● Before executing actual logic, we can validate all the request parameters
and body parameters to satisfy the intended schema.
● Through doing so, before executing real logic, we can throw an error at the
user input that the requested body is not correct.
Always Await Promises before Returning to Avoid a Partial Stacktrace
● ESLint is one of the most common linting kits, which is used to check potential
code errors and also check code types to conform with best practise standards.
● There are several linting tools available.
● It detects spacing problems in any potential patterns of code that could lead to
any security risks as well as possible future app-breaking.
● Other tools are also available that format code automatically and place it in a
more readable way.
● It also resolves minor syntax errors at the end of each sentence, such as adding
semicolons, etc.
Name Your Functions
● Many of the functions that may include closures and callbacks can be
called.
● You may limit the use of functions which are anonymous.
● Make sure you use a function called Naming.
● Naming will allow you to easily execute and then take a memory snapshot
of what you want.
Use Const Over Let, Do Not Use Var
● Const variables allocated can not be updated, this will help you avoid several times
from using a single variable so that we can keep our code safe.
● We'll use the let keyword in certain situations where we need to re-assign variables.
● For example, we can use let in a loop if we want to re-declare the variable value.
● Apart from this, the domain has been blocked by "let variables," meaning they are
accessible within a specific block where they are declared.
● It is possible to use variables declared using var anywhere within the function.
Use of Strict Equality Operator (===)
● Instead of weaker abstract equality operator = ==, use the strict equality
operator ===.
● == will convert two variables to a similar form and then compare them while
=== does not type case variables and guarantees that all variables are
identical and of the same type.
Don’t Use Callbacks, Instead Use Async Await
● In all node js versions above Node 8 LTS, Async-await is supported.
● To better deal with asynchronous code, we can minimise the use of
'callbacks' and 'promises'.
● It makes the code appear synchronous, but it's a non-blocking mechanism in
fact.
● The best thing we can do with async-await is to compact code and render
the syntax of code like try-catch.
Using Arrow Functions (=>)
● Arrow functions make the code more compact and maintain the root
function's lexical context (i.e. this).
● It is, however, a suggestion to use async-await applications when working
with old APIs that can accept promises or callbacks to stop the use of
functional parameters.
Node.js Security Best Practices
● This raises the possibility of database abuse when you often use JS strings or
string concatenations.
● This practise renders your data invalidated and highly vulnerable to SQL injection
attacks by the created application.
● For ORMs like Sequelize and Mongoose, in-built protection against certain SQL
injection attacks is available.
● In order to prevent these attacks, you must always use the built-in indexed
parameterized queries supported by Object-Relational Mapping/Object Document
Mapper ORM/ODM or database libraries supporting indexed parameterized queries.
Prevent DOS Attacks by Using Middlewares
● You can build impactful Node js applications with stable HTTP headers to
prevent clickjacking, cross-site scripting (XSS attacks) and other malicious
attacks.
● We can use plug-ins like the easy-to-configure helmet and create our own
security rules for Node.js.
Control Request Payload Size
● We want to ensure that all Node.js applicants embrace them from the
beginning of their development journey to deliver high-quality production
apps by enlisting the industry-standard Node.js best practises that are
adopted by us.
● For advanced developers looking to hone their Node.js abilities, these best
practises can also be equally useful.
● You can easily enhance your application efficiency with the aid of these
coding best practises, style guides and techniques.
References
1:https://www.tatvasoft.com/blog/node-js-best-practices/