☕ javascript

or, the "good" part. 😜 or, who are we kidding, it’s actually TypeScript these days.

js is “on fire” these days. 😝js is “on fire” these days. 😝

tl;dr


JS, ahem, I mean TS for newbies

despite the image at the top of this section, i ❤ javascript (typescript) so hard (tbh, typescript has taken over!). i’ve been coding in it since the 90’s and it’s only gotten better over the years.

if you’re absolutely new to JS, start here at the Mozilla Developer Network (or MDN). they’re the people that make Firefox and have the best reference guides for JS. in general though this guide assumes you’ve got a base understanding of JS so go forth and mess around with the language as much as you can before moving on to the rest of the more complicated stuff.

playgrounds

an easy way to get started is by checking out some of these tools that let you play around with the language. another great way is to a project that you like and checking out it’s code. view the source, luke!

  • CodeSandbox: lets you mess around with a React app in real-time.
  • CodePen: a social development environment for front-end designers and developers.
  • node’s REPL: most coding environments provide something called a REPL which lets you mess around with the code on the command line. just type in node on your command line and you should be able to try out some random code.
  • Glitch: friendly community to learn and play around with code.
  • RunKit: much like node’s REPL but online with some fancy UI.
  • npm sandboxing: you can take any package from npm and play around with it to see what it does:
mkdir sandbox
cd sandbox
npm init -y # create an npm project. -y means use defaults
npm install --save <package name>

developer tools

to be able to use JS effectively, you’ll need to have a set of tools to give you visibility into what’s happening and fiddle with your code. this is the absolute best way to learn. read the section on Chrome DevTools to learn how those tools can help you.


react + (facebook) friends

let’s get something straight: vanilla JS is something you absolutely should know. you need to understand the underlying principles and fundamentals of the frameworks you’ll be using so that you can effectively use them.

that being said, practically speaking, you won’t be writing vanilla JS a lot of the time and a well-chosen suite of frameworks will help immensely in your quest. a lot of the best of breed frameworks have come from a Cambrian explosion emanating from Facebook’s developer team. Google has tried through many, many, iterations to provide compelling alternatives but we should have seen the downward trend with frameworks ever since they started with the ill-conceived GWT. (i say this with love, y’all, since i used to work at Google. their contributions to browser tech and tools are amazing, but their frameworks have always been lagging.)

React

the way to write your application these days. if there’s one place to make sure you devour all the documentation, it’s here. go through the tutorials and starter guides (using create-next-app, mentioned in a section of its own below, is also a good leg-up.)

JSX a compelling feature that comes bundled with React is it’s ability to describe HTML and custom components within JS itself. this was high heresy not long ago (much like CSS-in-JS is still heresy in lots of circles but gaining traction.)

an example:

const element = <h1 className="greeting">Hello, world!</h1>;

underneath the hood, the code will be transformed into:

const element = React.createElement(
'h1',
{className: 'greeting'},
'Hello, world!'
);

tips

  • you don’t need to import React anymore directly with version 17+ to get JSX working.
  • adding React.StrictMode to your tree can help you with migrations.

GraphQL

GraphQL is a language that lets your client talk to the server to get data it needs in an efficient and forward-compatible way. there’s a lot to learn here and since it can be some of the more mind-bending stuff to learn in the React-verse, i recommend checking out this great intro tutorial to let your brain wraparound how it works.

as an alternative, SWR is a lighter weight option, less fully featured but an easier integration.

Apollo because GraphQL can be complex there are some great frameworks built around it. i recommend using Apollo to get you up and running with GraphQL quickly. to install:

npm i graphql graphql-tools graphql-tag apollo-server-express @apollo/client body-parser express

in addition, check out:

  • Robin Wieruch’s server and client tutorials: great intro tutorials for GraphQL and Apollo (by the way, i don’t recommend reading Apollo’s default tutorial (here, if you’re interested) — that one is overly complex and annoying to follow.)

gRPC in general, i would agree with this StackOverflow blog post about when to use GraphQL and when to use gRPC: “Use GraphQL for client-server communication and gRPC for server-to-server.”

<strike>React Redux</strike>

probably the more cultish side of the React-verse 😛. you’ll find a lot of acolytes and haters here. i actually might not recommend Redux for you, at least not off the bat. it’s another one of those mind-bending parts of the React world that can be a lot to take in. besides, even the creator suggests that sometimes it can be unnecessary. furthermore, Dan Abramov went on to say:

but also 🙂:

React Native

allows you to build native mobile apps using React. i don’t have much experience here but i hear good things and that it’s getting better over time. related libraries that are of interest: Expo, Yoga, Flutter. a great starter library is Tamagui.

looking forward

server components: interesting tact to address bundle size and performance for fetching data.


create-next-app

there’s a lot that goes into a javascript app these days. a lot. to that end, we’re gonna use the create-next-app tool to quickly get set up. create-next-app helps bundle together a lot of the popular tools that are part of modern development. i’ll get into what React is in the first place in a section below this one.

installation

first, make sure you have node, which is a JavaScript runtime:

brew install node

installing create-next-app:

npx create-next-app@latest
cd <name-of-your-new-project>
npm start

as an alternative, for this guide, i’ve created an even more comprehensive version of create-next-app called all-the-things that adds even more tools straight out of the box.

yarn create next-app --typescript --example https://github.com/mimecuvalo/all-the-things

usage

npm start # run development server
# to run with https, do HTTPS=true npm start
npm run build # build production files
npm test # Launches the test runner in the interactive watch mode.

you’ll find several folders and properties that are relevant to you:

  • public: let’s you add assets that you don’t need compiled by webpack. this doesn’t necessarily mean images. learn more here.
  • src: contains all the files you need for your app. you’ll mostly be coding in here.
    • index.js: the main entry point for your code. webpack is pointed to this file by default.
  • environment variables: on top of the folders, you’ll also have environment variables in your control to pass in various settings to your app depending on the current environment. learn more here.

pulling back the curtain

there’s a lot of magic that create-next-app brings to the table. the bundler acts as the glue for these packages. let’s look at the different things that come bundled in create-next-app by default.

  • Babel: a transpiler that lets you use future JavaScript features today so that it’s supported by current browsers. you’ll hear these being called things like “ES6” or “ESNext” when talking about future versions of JS. (of note: object destructuring/spread, classes, async/await and much more).
  • ESLint: checks the JS for code-quality rules (e.g. no-unused-vars, no-implicit-globals, etc.).
  • Jest: gives you some pretty great JS testing. use by running npm test.
    • coverage reporting: will show how much of your code is covered by tests.
  • PostCSS: enables lots of nice CSS capabilities, including the following:
    • postcss-preset-env: lets you use new/experimental (stage 3+) CSS features today. this depends on your browserslist field in package.json. (historical note: postcss-preset-env was previously known as “cssnext”)
    • autoprefixing: adds compatibility support for different browsers.
    • CSS Modules: let’s you import CSS into your JS. name your css files *.module.css to take advantage.
  • Progressive Web App (PWA) with Service Worker: gives your app offline capability and faster loading times (note: disabled by default. you can enable in index.js by switching serviceWorker.unregister(); to be serviceWorker.register();.)
  • React + JSX: obviously 🙂.
  • other misc features:
    • error overlay: if there’s a compile, lint, or type error, a helpful overlay on the site will show what’s wrong.
    • hot module replacement (HMR): when you change the code during development the new changes will be reflected in your browser, preserving the current state.
    • minifier: in production, reduces the size of the code bundle as much as possible.
    • obfuscation: in production, mangles the variables/functions of your code so it’s unreadable.
    • absolute imports: don’t have to do import foo from '../../../../foo' anymore.

app router

learn more about all the ways the Next.js App Router works with this interactive demo.


all-the-things

as mentioned above, i’ve created a custom template that plugs into create-next-app such that it gives you ✨ ALL THE THINGS ✨ that are mentioned in this entire guide bundled in by default. love it ❤ or leave it 🏃‍♀️.

features:

  • accessibility (a11y) analyzer: via axe. in the bottom corner of CRA you’ll see a menu that will give you a list of items your site is violating in terms of a11y.
  • authentication: via Auth0. gives you the ability to login using Google/Facebook.
  • bundle size analyzer: via source-map-explorer. do npm run analyze after creating a build.
  • component Libary (UI): via MUI.
  • CSP nonce: adds example code in _document.ts
  • data fetching: adds GraphQL, Apollo, and GraphQL Code Generator.
  • documentation: adds some standard and GitHub-specific Markdown files using best practices. files include:
  • error boundary: adds a top-level one to the app.
  • error pages: 401, 404, 500.
  • error reporting: listens to window.onerror and reports JS errors to the server for debugging.
  • humans.txt / robots.txt: adds stubs of these files.
  • Jest: some setup nicities.
  • i18n: via react-intl.
  • kill switch: runs a client health check every 5 minutes to see if the client is still valid.
  • libraries: adds lodash by default.
  • Open Graph: adds stub for social media embedding.
  • OpenSearch: adds stub file so that you can add search queries to your site later.
  • ORM: via prisma.
  • perf indicator: in the bottom corner of the app, it will display render times.
  • Prettier: adds linting upon commit. also adds import sorting.
  • structured data: via JSON-LD.
  • styleguide: via Storybook.

security

as mentioned in +🛠️ tools of the trade: security, every engineer is a security engineer. you need to act like it and protect your app from the forces acting against you.

in addition to the protections at the server level, there are some things to implement at the application level as well. this is called “defense in depth”, adding multiple layers of security to protect yourself.

  • escaping user data (via React): the easiest, most common mistake is taking user-submitted data to your site and spitting it out somewhere else. a user can easily submit malicious HTML/JS that would then attack other users on the site. you can take a great stride to avoiding this by using a framework, like React, that escapes user data by default.
  • data validation: i can’t recommend a particular framework/library here but you should take care to validate that the data you get from your users is what you expect it to be. if you’re expecting a date like 10/12/2012 but instead get alert(1) you should call shenanigans.
  • bcrypt: if you need to deal with passwords on your site, this library should be in your toolset.
  • reCAPTCHA: if you need to deal with bots, this tool from Google will help prove if you’re a robot or not.
  • npm package security: you never really know what possibly malicious code you’re pulling in to your repository via npm. one way to help combat this attack vector is using exact versioning. set this by doing npm config set save-exact true
  • subresource integrity: when including external scripts, you can add a hash via the integrity attribute. this verifies that the script hasn’t changed behind your back.

fun articles to read (to make you more paranoid):


libraries of interest

if there’s one thing that will last after the earth is gone, it’ll be cockroaches and js libraries. there are so many of them. try not to overdo it, because with each library you add, you become beholden to it.

some brief recommendations, as of 2023

other notes

  • by the way, there are other libraries smattered throughout this guide (e.g. Material-UI) but those are more frameworks to “buy into” vs. handy tools that you can pull into a particular file.
  • to create your own libraries, there exists create-react-library and its companion repository, react-modern-library-boilerplate.

resources