Use a React Component from NPM in an MDX File with Gatsby MDX
lessonDuration 46sFree
MDX allows you to use JSX and React components directly inline in your Markdown. Here's how.
Browse
Find courses, lessons, articles, talks, and podcasts.
164 results for "gatsby"
Showing 121–144 · Page 6 of 7
lessonDuration 46sFree
MDX allows you to use JSX and React components directly inline in your Markdown. Here's how.
course
A short list of screencasts to cover essentials of [Gatsby](https://www.gatsbyjs.org/) to get started and have enough knowledge to become dangerous. The content comes from multiple instructors that have each covered different essentials, this cherry picks some of the most important concepts. Videos in this collection cover these topics: - installing plugins - creating pages - navigating between pages - adding optimized images - theming your styles - deploying your site
course
lessonDuration 1m 22sFree
Gatsby’s `createPage` action allows for additional data to be passed in via `context`. In this lesson, we will add a processing step to include links between posts, and update our templates to conditionally display them as appropriate.
lessonDuration 1m 26sFree
In order to display the generated HTML from a Markdown post, we will build a GraphQL query and pass its data into a Template component that makes use of React’s dangerouslySetInnerHTML DOM element.
podcast
<p>Marcy Sutton is the Head of Learning at GatsbyJS, but what does that mean? One of Gatsby's core focuses is the community, and a part of that is making the experience with Gatsby as friendly as possible. A large part of making Gatsby friendly is having <i>excellent</i> documentation, so that learning and debugging experiences would be smooth. </p><p>So the learning experience is smooth but what is Gatsby's potential on the web? Marcy talks about how Gatsby has the potential to make a huge impact. Currently WordPress is powering about a third of the web, that's huge, but it has its issues. WordPress is centered around the authoring experience but the front-end experience is not good. Gatsby is looking more towards the future, it doesn't use a database, it can build out static HTML, it's accessible, and it's also democratizing the experience with a themes ecosystem. </p><p>This brings up the point that JavaScript is eating the web and it's making it more difficult for folks who've had a different intro to webdev. This is a real challenge and people are having their careers impacted, what can we do to reconcile this? The decisions made by tech teams aren't considering this when the pick the technologies that they use, they're picking tech that's going to deliver a high preformance application, where does HTML and CSS fit into this? Marcy discusses how we can bridge the gap and find ways to include people with different skill sets. </p><p>Marcy also discusses the inclusive community that she has helped build, NW Tech Women, a small group out of Bellingham WA that hosts social events, but also volunteers and pairs with non-profits to make a community impact. </p><hr /><h3>Transcript</h3><p><a href="https://egghead.simplecast.com/episodes/7c3086d2/transcript">"Heading Gatsby's Learning Experience and Bridging Gaps - with Marcy Sutton" Transcript</a></p><h3>Resources:</h3><ul><li><a href="https://twitter.com/NWTechWomen">NW Tech Women Twitter</a></li><li><a href="http://www.blackgirlscode.com/">Black Girls Code</a></li><li><a href="https://www.gatsbyjs.org/">GatsbyJS</a></li></ul><h3>Marcy Sutton:</h3><ul><li><a href="https://twitter.com/marcysutton">Twitter</a></li><li><a href="https://marcysutton.com/">Website</a></li><li><a href="https://github.com/marcysutton">GitHub</a></li></ul><h3>Joel Hooks</h3><ul><li><a href="https://twitter.com/jhooks">Twitter</a></li><li><a href="https://joelhooks.com/">Website</a></li></ul>
podcast
<p>Jason Lengstorf is a developer on the GatsbyJS team.</p><p>Jason didn't start his career even remotely in the tech field. He was a musician.<br />Jason's band didn't have much money, so he learned design to make merch, learned some markup to edit their myspace, eventually learned to build a website for them, then learned backend so his bandmates could upload images and post things.</p><p>Jason talks about Gatsby's plans to compete with the more seamless WordPress model. He also talks about gatsby's differences from WordPress and the use cases for each service.<br />One of Gatsby's strengths is how good it is for learning Javascript and React, you can quickly go from the command line to getting stuff on the screen in two minutes, much like create-react-app, the differences is that with Gatsby you get a data layer and a good deployment story.</p><p>Finally, they talk about what it's like to manage a repo that has 964 contributors, 5500 commits, and 936 issues. It was more chaotic in the early days, but they have brought on some people who are helping manage it and are defining better processes.</p><p>If you are interested in learning Gatsby, they have recently put much work into revamping their official tutorials.<br /><a href="https://www.gatsbyjs.org/tutorial/">Check them out here</a></p><hr /><h3>Transcript</h3><p><a href="https://egghead.simplecast.com/episodes/188eecc0/transcript">"Jason Lengstorf on GatsbyJS" Transcript</a></p><h3>Topics:</h3><ul><li>His early musical aspirations that lead to his career as a developer</li><li>Gatsby's goals in creating an agnostic unified data layer.</li><li>The differences between Gatsby and other static site generators</li><li>Gatsby 2 and its many performance upgrades</li><li>Managing a large and active repository</li></ul><h3>Resources:</h3><ul><li><a href="https://www.gatsbyjs.org/">Gatsby</a></li><li><a href="https://twitter.com/gatsbyjs">Gatsby on Twitter</a></li><li><a href="https://www.gatsbyjs.org/tutorial/">Gatsby Tutorials</a></li><li><a href="https://www.netlify.com/">Netlify</a></li></ul><h3>Jason Lengstorf:</h3><ul><li><a href="https://lengstorf.com/">Website</a></li><li><a href="https://twitter.com/jlengstorf">Twitter</a></li><li><a href="https://github.com/jlengstorf">Github</a></li></ul><h3>John Lindquist:</h3><ul><li><a href="https://twitter.com/johnlindquist?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor">Twitter</a></li><li><a href="https://johnlindquist.com/">Website</a></li></ul>
article
# Introduction This article is about my experience building a SaaS application. And while this won't be a step-by-step guide on how to build a SaaS app, I will be providing you valuable insight on what the process was like for me as well as teaching you about the methods and technologies that I used. Software as a Service (SaaS) is a business model whereby the user pays a subscription to access cloud-based services or an application. In my case, I wanted to build an educational course platform where users can purchase an individual course to own for life or pay a subscription to gain access to all premium courses. Before building this application, I had only used Stripe Checkout to process one-off payments. I wanted to use this opportunity to go a little deeper - primarily learning how Stripe handles recurring payments. I plan to implement what I have learned throughout this process into my [site](https://jonmeyers.io/), which will house my premium courses one day. The final version of this SaaS project ended up with a few third-party services, each handling their own piece of the puzzle and using webhooks to keep them in sync. Below is an architecture diagram representing the relationships between those services.  This article will focus on each chunk of the stack individually. I will talk through why I chose each technology and discuss any problems I ran into during the process. [Here is the project repo](https://github.com/dijonmusters/courses) for those after the code and a [live version of the final project named "Courses"](https://courses-saas.vercel.app/). FYI, payments are real! You have been warned, and thank you for your donation! 😆 # What will be covered? - High-level explanation of why certain technologies were chosen - Biggest problems encountered throughout and how they were solved - Next.js and the use cases for pregeneration vs serverside rendering - Hosting, secrets, and automatic deploys with Vercel - Prisma as an ORM, as well as the project's database schema and migrations - Using Auth0 for authentication, GitHub as a social provider, and webhooks to keep things in sync - Stripe for individual payments, subscriptions, and more webhooks! # What will not be covered? - A step-by-step guide for building a SaaS project - I wrote a [blog article each week](https://jonmeyers.io/blog/build-a-saas-platform-with-stripe) as I was building the project, which goes into more granular detail. [](https://egghead.io/courses/build-a-saas-product-with-next-js-supabase-and-stripe-61f2bc20?utm_source=blog_post&utm_medium=course_cta&utm_term=supabase) # Tech stack - **Next.js** was used to build the UI, as well as the small chunks of server-side logic required for fetching gated content from Prisma, initiating authentication with Auth0, and payments with Stripe - **Vercel** was used as a hosting platform for the application and its serverless functions - **Prisma** provides a beautiful query-building language to abstract away those scary, complex SQL queries - **Supabase** was used to host a Postgres database instance - it is capable of so much more around authentication and real-time database events, but we already had those pieces solved - **Auth0** was used to authenticate users with GitHub, manage sessions and protect both client and API routes in Next.js - **Stripe** was used to process payments, subscriptions and host a customer portal for users to manage their subscription and payment information # The app When considering different framework options to build the app, I had already decided that React would be the foundation - I have the most experience with it, and it makes me the most productive. I wanted to be able to pre-generate (build static pages) any un-gated/public content. This gave me a few options: **Handcrafted React and Node server** ❌ Too much work! **Gatsby** ✅ Awesome framework ✅ Static generation of pages at build time **Next.js** ✅ Also an awesome framework ✅ Static generation of pages at build time ✅ Server-side rendered pages ✅ API routes (serverless functions) I chose Next.js primarily because of its server-side rendering. Authentication would be a big part of this project, so I wanted to have an easily accessible server to handle all that secret stuff! While Gatsby spins up a server when building an application, that server does not exist when your users are using the app. Therefore, if I wanted to do secret stuff, I would have to manage another server! That sounds like too much work! Additionally, with so many different technologies being used already, and one of the main outcomes of this project being a case study to share with people, I didn't want to throw in the mental overhead of GraphQL, which is somewhat unescapable with Gatsby - GraphQL is awesome. Still, we can cover it at another time! ## Pregeneration (SSG) Pregeneration is the process of fetching all the data for a page when building the application. This means we can request data from slow servers, do expensive computational tasks, etc., without every user needing to sit and watch a loading spinner. We do all these slow tasks once, build static HTML pages with the data, and then serve them as static assets - much cheaper to host and scale! Next.js makes pregeneration super easy! All you need to do is export a function called `getStaticProps` from a page-level component. It will pick this up when building the application, run the function and inject the result into the component. Here is a simple example of how this can be used. ```jsx const BlogsPage = ({ blogs ) => blogs.map(blog => <p>{blog.title}</p>) export const getStaticProps = async () => { const blogs = await getBlogPosts() // fetching from remote API return { props: { blogs, }, } } export default BlogsPage ``` Here is an example from our SaaS application where we need to fetch all of the `prices` from Stripe, then iterate over each one and request its associated `product`. ```jsx const PricingPage = ({ plans }) => ( // render each plan ) export const getStaticProps = async () => { const { data: prices } = await stripe.prices.list() const plans = await Promise.all( prices.map(async (price) => { const product = await stripe.products.retrieve(price.product) return { id: price.id, name: product.name, price: price.unit_amount, interval: price.recurring.interval, currency: price.currency, } }) ) return { props: { plans, }, } } export default PricingPage ``` In this example, we have two subscription plans, so we would be making three requests - one for the list of `prices` and then an additional request for each one's `product`. Imagine if we had one hundred products. What about a thousand! This could take a while and provide a pretty bad experience for our users 🙁 Remember, happy customers, like to buy our things! If we make these requests when we build our application, then they only happen once - when we deploy. No users are sitting around and waiting for us to deploy. When they visit the site, they get a super snappy pregenerated static page that doesn't need to rely on any third-party services for its data! Pregeneration works amazingly well for public content - pages where you don't care who the user is. Great for marketing pages and things that don't need to change frequently - such as a pricing page. If the page requires a user to be signed in or you are rendering different content for different users - such as a user dashboard - pregeneration is no longer a viable option. The problem is that when the server is building these static pages, there is no user! ## Server-side Rendering (SSR) That's where server-side rendering comes to save the day! This process runs when the user requests the page rather than when the server builds the application. Therefore, we know who the user is and can determine what they should and shouldn't access. Additionally, because this logic is running on the server, we can do secret things - such as fetch premium content from Prisma or check whether the user has a particular role - without worrying whether the user has tinkered with it. NEVER TRUST ANYTHING ON THE CLIENT! We can only trust our server-side code! Again, Next.js makes it super simple to run some server-side code. We export a function called `getServerSideProps`, and it will automagically turn it into a serverless function that runs when the user requests the page. Again, the data returned is injected into the component and displayed to the user. Here is a simplified example of this logic. ```jsx const SecretStuffPage = ({ secretStuff ) => ( <> <NormalStuff /> {secretStuff && <SecretStuff /> </> ) export const getStaticProps = async () => { let secretStuff = null if (user.canSeeSecretStuff) { secretStuff = await getSecretStuff() } return { props: { secretStuff, }, } } export default SecretStuffPage ``` And here is a more realistic example from our application where we only want to display a lesson's video URL if the course is free, paid for, or has an active subscription. ```jsx const LessonPage = ({ videoUrl }) => videoUrl ? ( <video src={videoUrl} /> ) : ( <button onClick={buyCourse}>Buy course</button> ) export const getServerSideProps = async ({ req, res, params }) => { const { slug } = params const session = await getSession(req, res) const email = session?.user?.email let videoUrl = null let user = null const lesson = await getLesson(slug) if (email) { user = await getUser(email) } const userAllowedCourse = lesson.course.price === 0 || user?.isSubscribed || user?.courses.find((course) => course.id === lesson.course.id) if (userAllowedCourse) { videoUrl = lesson.videoUrl } return { props: { videoUrl }, } } export default LessonPage ``` In the above example, `videoUrl` is either null or a URL for the lesson's video, depending on whether the user is allowed to see this content or not. By only returning the bits of data that the user is allowed to see, we make sure that the secret stuff remains secret! If we had returned the entire lesson from `getServerSideProps` and simply checked in the component whether we should display it or not, then that data has still been sent across from the server to the client. The secret stuff is no longer secret! Take this example. ```jsx const LessonPage = ({ lesson, user }) => { console.log(lesson) const userAllowedCourse = lesson.course.price === 0 || user?.isSubscribed || user?.courses.find((course) => course.id === lesson.course.id) return userAllowedCourse ? ( <video src={videoUrl} /> ) : ( <button onClick={buyCourse}>Buy course</button> ) } export const getServerSideProps = async ({ req, res, params }) => { const { slug } = params const session = await getSession(req, res) const email = session?.user?.email let videoUrl = null let user = null const lesson = await getLesson(slug) if (email) { user = await getUser(email) } return { props: { lesson, user }, } } export default LessonPage ``` If we were to run this in the browser, it would seem equivalent to our previous example - the video would only display if the user were allowed to see it. However, if we open the console, the entire lesson object will be displayed - including the `videoUrl`. Once we have sent the page to the browser, it runs on the user's machine and is very easy to tinker with! Therefore, if we only return the bits of the data that the user is allowed to see from `getServerSideProps`, then we can keep the secret stuff secret. Server-side rendering with `getServerSideProps` allows us to encapsulate some logic that we need to run on the server without needing to maintain one. <EmailSubscribeWidget /> # Hosting Next up, we need a place to host this application to share it with the world! Again, there are many options that vary greatly in the amount of control vs. work done for you. Since hosting the application is not the thing my users care about, I wanted to use a service that did as much of the heavy lifting as possible. Netlify and Vercel were the main options I was considering. Netlify is awesome and has recently released a [zero-config plugin that enables all the SSR Next.js magic](https://www.netlify.com/blog/2021/03/16/try-the-new-essential-next.js-plugin-now-with-auto-install/). However, I chose to go with Vercel as they are usually slightly ahead of the curve with new Next.js features - probably because they are the creators and maintainers of that too! Hosting the application was super simple with their CLI. ```jsx vercel --prod ``` That's it! This will deploy a new version of your application with a `.vercel.app` domain. This is now hosted live on the Internet and can be seen by anyone in the world with an Internet connection. Very cool! ## Automatic deploys Automatic deploys with GitHub were also a breeze to configure with Vercel. Just push the code to GitHub, authorize Vercel and tell it which branch.  It will now automatically deploy a new version of our application anytime new commits are pushed to the `master` branch of the `courses` repo. ## Preview deployments Another awesome thing Vercel gives us for free is [Preview Deployments.](https://vercel.com/docs/platform/deployments#preview) It will listen for any changes that we push to branches other than `master` - such as opening a new Pull Request - and automatically deploy a new preview version of our application with its own unique URL. This is an awesome way to test new features or get feedback from the team before something goes live! ## Secrets Next up, we need to tell Vercel all of our secrets! Secrets are the variables our application needs to do all the secret things when running in production. These often include API keys to send authenticated requests to a service, database connection strings, and special values we need for auth stuff. Vercel does environment variables a little differently from other platforms. You first create the secret, then link its value to a particular environment variable. This gives you more control over sharing secrets across multiple projects and granting or restricting particular environments access - e.g., available in production and preview, but not development. Again, super simple to configure. Head over to Settings > Environment Variables and create what you need. There are three different types of Environment Variables in Vercel: 1. Plaintext - things that don't need to be secret - such as API_URL 2. Secret - sensitive values - such as API keys, DB connection strings etc 3. Provided by system - values populated by the system during deployment - such as Preview deploy URL I used `secret` for all of my environment variables. These are made available to your API routes (serverless functions) and any functions that run on the server - `getStaticProps`, `getServerSideProps`, etc. If you would like an environment variable to be available in your client-side code, it must be prepended with `NEXT_PUBLIC_`. In our SaaS application, we have a publishable key from stripe called `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY`. You can run the `vercel dev` command locally to run a development server with access to secrets that you have granted the Development permission to, however, I find it easier to just create a `.env` file for secrets running in dev. This is automatically loaded by Next.js and applies the same rules - environment variables available to server-side stuff, variables prepended with `NEXT_PUBLIC_` available client-side. This also means you don't need to add a second copy of your secrets just for dev, or use the same secrets across all of your environments - which is a bad idea! Vercel is an awesome host that makes deployments and hosting super simple. They take care of all the difficult stuff so you can focus on building the thing that makes you money! Additionally, they have a super generous free tier. If you hit the ceiling then you probably have enough users to justify paying Vercel! # Database The next thing we need to consider is what kind of database we need. The first question to ask is whether you actually need a database at all? Could you get away with just using content in markdown files? In my case, I will need to store course content - this sounds great for markdown files - but I also need to know which users have bought particular courses and whether they have subscribed. This might be getting a bit hard to do with markdown. Since we already know we will need to build relationships between different bits of data, a relational database sounds like a good option. Again, there are many options for database hosts with varying levels of management. I decided to go with [Supabase](https://supabase.io/) due to its simplicity of getting up and running. They are an open-source alternative to Google's Firebase and offer so much more than what we are using them for here. Creating a hosted Postgres DB was as simple as authenticating with GitHub and creating a new project. The connection string can be found at Settings > Database > Connection String. Now we need to decide how we want to talk to this database. I'm a huge fan of not manually writing SQL! I can fumble through a query or two but don't trust myself to do it in a performant way. I also have a background in Rails and really like how ORMs (object-relational mappers) abstract away the complexity of writing queries - it feels more like writing code. Prisma is a fantastic ORM that makes building queries that request data across multiple tables super simple and easy to read. Here is an example where we want to find a user based on their email. ```jsx const user = await prisma.user.findUnique({ where: { email: 'jon@gmail.com' } }) ``` If we wanted to also select the courses they had enrolled in (data from another table), we can just tell the Prisma query to include it. ```jsx const user = await prisma.user.findUnique({ where: { email: 'jon@gmail.com' }, include: { courses: true }, }) ``` ## Schema Prisma uses a `schema.prisma` file to define the structure of the database. Models represent different tables and declare the relationships between them. This is the final schema for our SaaS project. ```jsx model User { id Int @id @default(autoincrement()) email String @unique stripeId String @unique isSubscribed Boolean @default(false) courses Course[] createdAt DateTime @default(now()) } model Course { id Int @id @default(autoincrement()) title String @unique description String lessons Lesson[] users User[] price Int slug String @unique createdAt DateTime @default(now()) } model Lesson { id Int @id @default(autoincrement()) title String @unique description String courseId Int course Course @relation(fields: [courseId], references: [id]) videoUrl String slug String @unique createdAt DateTime @default(now()) } ```  A many-to-many relationship - such as a user's courses - can be easily queried like this. ```jsx const user = await prisma.user.findUnique({ where: { email: 'jon@gmail.com' }, include: { courses: true }, }) user.courses // this is an array of courses the user has enrolled in ``` A one-to-many relationship - such as a lesson's course - can be queried like this. ```jsx const lesson = await prisma.lesson.findUnique({ where: { slug: 'intro-to-js' }, include: { course: true }, }) lesson.course // this is the course the lesson belongs to ``` No need for scary joins! ## Migrations Prisma uses migrations to track changes to the database structure - such as adding a new table or column. This is inevitable as a project grows, so having a way to make these incremental changes without breaking things is a must! Prisma validates each change before applying the migration and altering the database structure. This means you get helpful errors and warnings if you try to do something that will modify or destroy existing data. For example, if I tried to remove the ID column on our user model, I get the following helpful error: ```jsx Error validating field `users` in model `Course`: The relation field `users` on Model `Course` references `User` which does not have an `@id` field. Models without `@id` can not be part of a many to many relation. Use an explicit intermediate Model to represent this relationship. ``` To create a migration you just modify the `prisma.schema` file to reflect what you want to change and then run this command to tell Prisma to update the database. ```jsx npx prisma migrate dev ``` ## Seeds Another thing I found particularly useful when making lots of changes to the DB was a `seed.js` file. This can be populated with test data, which makes playing around with database structure much more fun! If you break things too much, just reset the DB and populate with the seed file again! Here is an example course from our SaaS project. ```jsx const { PrismaClient } = require('@prisma/client') const prisma = new PrismaClient() async function main() { await prisma.course.upsert({ where: { title: 'Introduction to JavaScript' }, update: {}, create: { title: 'Introduction to JavaScript', description: "This is a gentle introduction to a super awesome programming language. You're going to love it!", price: 13000, slug: 'introduction-to-javascript', lessons: { create: { title: 'What even is the console?', description: 'The console is where we see super cool stuff!', videoUrl: 'https://www.youtube.com/watch?v=PFljjv6j_YM', slug: 'what-even-is-the-console', }, }, }, }) } main() .catch((e) => { console.error(e) process.exit(1) }) .finally(async () => { await prisma.$disconnect() }) ``` > Using `upsert` makes this file *idempotent*, meaning it can be run over and over again without filling up our database with unnecessary records. # Auth Since we will be locking down premium content to only display for people who have purchased a course or have a subscription, we're going to need to know who they are. For this, we will need them to create an account. Like all of these services, you can manage as much of the process and have as much control as you want. Since I have had fairly limited experience with building authentication solutions, I want something else to stay up to date with all the security best practices and tell me whether a user should have access or not. Auth0 does exactly this - and has done for many, many years. It is yet another awesome service that has a super generous free tier! They also integrate with a huge number of social providers - even things like Strava and Fitbit. This means that users don't need to create yet another account just to use our application. Since my product will be pretty heavily targeted at software developers, I set up the only authentication method to be with GitHub. ## Auth0 and Next.js So, how easy is it to integrate Next.js with Auth0? Install an NPM package and copy in a small amount of starter code! Super easy! Auth0 has built an amazing integration library called `nextjs-auth0`. I recommend checking out their [Getting Started](https://github.com/auth0/nextjs-auth0#getting-started) guide to get everything configured. This library takes care of all the session management logic between the Next.js application and API routes. It also creates new API routes for login, logout, token exchange, and a "me" page to check who is currently logged in. Additionally, it includes a collection of helper functions that we can use in different parts of our application to determine who the user is and whether they should be able to view the content. Check out the [Examples page](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md) to learn more about when to use each one. ## Rules [Auth0 Rules](https://auth0.com/docs/rules) are serverless functions that allow us to run some code during the authentication process - after a user has signed in but before they are redirected to our application. This is the perfect time for us to create a new Prisma user and anything else we need to do to keep our local bits of data in sync with Auth0. This is how we make a request to our SaaS project and tell it to create a new Prisma user. ```jsx async function (user, context, callback) { await request.post('https://courses-saas.vercel.app/api/auth/hooks', { body: JSON.stringify({ email: user.email, }) }); callback(null, user, context); } ``` Since we only want to do this the first time the user logs in, we can set some metadata on our Auth0 user to let us know this has already been done before. ```jsx async function (user, context, callback) { user.app_metadata = user.app_metadata || {}; if (user.app_metadata.localUserCreated) { callback(null, user, context); } else { try { await request.post('https://courses-saas.vercel.app/api/auth/hooks', { body: JSON.stringify({ email: user.email, secret: configuration.AUTH0_HOOK_SECRET, }) }); user.app_metadata.localUserCreated = true; await auth0.users.updateAppMetadata(user.user_id, user.app_metadata); callback(null, user, context); } catch (err) { callback(err); } } } ``` We are also sending across a `secret` value to validate that this request is coming from Auth0. This is our API route to receive the request from Auth0. ```jsx import { PrismaClient } from '@prisma/client' const prisma = new PrismaClient() module.exports = async (req, res) => { const { email, secret } = JSON.parse(req.body) if (secret === process.env.AUTH0_HOOK_SECRET) { try { await prisma.user.create({ data: { email }, }) } catch (err) { console.log(err) } finally { await prisma.$disconnect() res.send({ received: true }) } } else { res.send('You forgot to send me your secret!') } } ``` Auth0 will halt the authentication flow until it receives the response from our API. This will eventually timeout and fail to authenticate the user if we forget to send a response. Best not to do anything too computationally expensive here, but perfect for creating a new DB record! This is what the interactions between our application, Auth0 and Prisma look like when a user logs in for the first time.  # Payments Now for the exciting bit! Let's make some money! Stripe is an incredible service for dealing with payments. They take on all the scary credit card stuff so that our application doesn't even need to know about it. We just subscribe to particular Stripe events and update our database accordingly. Again, they have a huge security team constantly updating how they process payments and store data. I do not want that responsibility! Make sure to check out their [pricing page](https://stripe.com/en-au/pricing) to make sure you are happy with what they are charging. Given how easy they make it to set up credit card payments and complex subscriptions without needing to pay upfront, I am pleased with it! ## Creating a Stripe customer Since we will be using Stripe pretty extensively - once-off payments, subscriptions, and a customer portal - we probably want to create a Stripe customer as early as possible and store their ID with our Prisma user. Since we already have a serverless function to keep Auth0 and Prisma in sync, let's also add the Stripe logic. ```jsx import initStripe from 'stripe' import { PrismaClient } from '@prisma/client' const stripe = initStripe(process.env.STRIPE_SECRET_KEY) const prisma = new PrismaClient() module.exports = async (req, res) => { const { email, secret } = JSON.parse(req.body) if (secret === process.env.AUTH0_HOOK_SECRET) { try { const customer = await stripe.customers.create({ email, }) await prisma.user.create({ data: { email, stripeId: customer.id, }, }) } catch (err) { console.log(err) } finally { await prisma.$disconnect() res.send({ received: true }) } } else { res.send('You forgot to send me your secret!') } } ``` This is what the interaction looks like between our application, Auth0, Stripe and Prisma when a user signs in for the first time.  ## One-off payments To charge a customer for a course, we need to create a new API route to set up a Stripe session. Remember, we cannot trust any data coming from the client - especially the price! Think about the minimal amount of information you actually need from the user to know what they would like to purchase. This is usually just an ID of the product and the quantity they would like to purchase. Since it doesn't make sense for one user to purchase multiple copies of a course, we have hard-coded the quantity. ```jsx import { withApiAuthRequired, getSession } from '@auth0/nextjs-auth0' import initStripe from 'stripe' import { PrismaClient } from '@prisma/client' const prisma = new PrismaClient() const stripe = initStripe(process.env.STRIPE_SECRET_KEY) module.exports = withApiAuthRequired(async (req, res) => { const { courseId } = req.query const { user: { email }} = getSession(req, res) const user = await prisma.user.findUnique({ where: { email }, }) const course = await prisma.course.findUnique({ where: { id: parseInt(courseId) }, }) await prisma.$disconnect() const lineItems = [ { price_data: { currency: 'aud', // swap this out for your currency product_data: { name: course.title, }, unit_amount: course.price, }, quantity: 1, }, ] const session = await stripe.checkout.sessions.create({ customer: user.stripeId, payment_method_types: ['card'], line_items: lineItems, mode: 'payment', success_url: `${process.env.CLIENT_URL}/course/${course.slug}`, cancel_url: `${process.env.CLIENT_URL}/payment/cancelled`, payment_intent_data: { metadata: { userId: user.id, courseId, }, }, }) res.json({ id: session.id }) }) ``` So there is a bit going on in this example. 1. We need to know who the user is so this needs to be an authenticated API route. We're using `withApiAuthRequired()` to help us with that. 2. We get the course ID from the dynamic part of the URL. 3. We get the user's email from the session. The session contains session information from Auth0, but is missing things like their Prisma and Stripe ID. 4. We make a request to Prisma for the full user. 5. We make a request to Prisma for the full course. We don't want to trust the client to send us data about the course, just which one they would like to purchase. 6. We create an array of line items that the user would like to purchase. We are just charging for a single item, but this still needs to be an array for Stripe to process it. 7. We create a Stripe Checkout session with some information about the transaction and pass this back to the client so they can be redirected to Stripe. 8. We are attaching some metadata to the session - user ID and course ID. This will be used when we configure webhooks. ## Subscriptions Subscriptions are significantly more complex than one-off payments. We need to keep a track of when to charge the user again, as well as store their card details and deal with all the edge cases when they want to change to a different plan or cancel their subscription altogether. Thankfully, Stripe does all the hard work so we don't need to worry about any of this. We just create our different pricing options as products in the Stripe dashboard, and create an API route to initiate the session. ```jsx import { withApiAuthRequired, getSession } from '@auth0/nextjs-auth0' import initStripe from 'stripe' import { PrismaClient } from '@prisma/client' const prisma = new PrismaClient() const stripe = initStripe(process.env.STRIPE_SECRET_KEY) module.exports = withApiAuthRequired(async (req, res) => { const { priceId } = req.query const { user: { email }} = getSession(req, res) const user = await prisma.user.findUnique({ where: { email }, }) await prisma.$disconnect() const lineItems = [ { price: priceId, quantity: 1, }, ] const session = await stripe.checkout.sessions.create({ customer: user.stripeId, mode: 'subscription', payment_method_types: ['card'], line_items: lineItems, success_url: `${process.env.CLIENT_URL}/payment/success`, cancel_url: `${process.env.CLIENT_URL}/payment/cancelled`, metadata: { userId: user.id, }, }) res.json({ id: session.id }) }) ``` It is actually fewer lines of code than a one-off payment! Amazing! Now that we have payments implemented we probably need to tell our Prisma DB that someone has purchased a course or updated their subscription. ## Webhooks Webhooks allow us to subscribe to particular events, and have Stripe let us know when they happen. Let's create a new API route to handle this. ```jsx import initStripe from 'stripe' import { buffer } from 'micro' import { PrismaClient } from '@prisma/client' const stripe = initStripe(process.env.STRIPE_SECRET_KEY) const prisma = new PrismaClient() export const config = { api: { bodyParser: false } } export default async (req, res) => { const reqBuffer = await buffer(req) const signature = req.headers['stripe-signature'] const signingSecret = process.env.STRIPE_SIGNING_SECRET let event try { event = stripe.webhooks.constructEvent(reqBuffer, signature, signingSecret) } catch (err) { console.log(err) return res.status(400).send(`Webhook Error: ${err.message}`) } const { metadata } = event.data.object const stripeId = event.data.object.customer switch (event.type) { case 'charge.succeeded': if (metadata?.userId && metadata?.courseId) { const user = await prisma.user.update({ where: { id: parseInt(metadata.userId), }, data: { courses: { connect: { id: parseInt(metadata.courseId), }, }, }, }) } break case 'customer.subscription.created': if (stripeId) { await prisma.user.update({ where: { stripeId, }, data: { isSubscribed: true, }, }) } break case 'customer.subscription.updated': if (stripeId) { await prisma.user.update({ where: { stripeId, }, data: { isSubscribed: true, }, }) } break case 'customer.subscription.deleted': if (stripeId) { await prisma.user.update({ where: { stripeId, }, data: { isSubscribed: false, }, }) } break default: console.log(`Unhandled event type ${event.type}`) } await prisma.$disconnect() res.send({ received: true }) } ``` This one is a little complicated as the `req` object we get from Vercel is structured differently to what Stripe is expecting. Let's break it down. 1. We export a `config` object to tell Vercel we want the raw request. 2. We compare the request we get from the user with Stripe's `constructEvent` function. This validates that the request was sent by Stripe and returns the webhook event object. If it cannot validate the request, it throws an exception, and we return an error to the client. 3. Next we determine which event has been received - `charge.succeeded` - user purchased a course. - `customer.subscription.created` - user subscribed. - `customer.subscription.updated` - user has changed their subscription. Since cancellation events are triggered separately, we can just trust the user is still subscribed. - `customer.subscription.deleted` - user cancelled their subscription. This is triggered when the subscription expires, rather than when they cancel. 4. Update our Prisma user. Webhooks can be tested locally using [Stripe's CLI tool](https://stripe.com/docs/stripe-cli). [Check out this article from the Stripe docs](https://stripe.com/docs/webhooks/test) to get it setup. Prod webhooks can be setup in Stripe's dashboard. This is the interaction between our application, Stripe and Prisma when a user subscribes.  ## Customer portal The last thing we need to set up is a customer portal. This will enable users to manage their own subscription and payment information. This can be configured via Stripe's dashboard `Settings > Billing > Customer Portal` and gives super granular control over what you would like customers to be able to change. A new portal session can be initiated from an API route like this. ```jsx import { withApiAuthRequired, getSession } from '@auth0/nextjs-auth0' import initStripe from 'stripe' import { PrismaClient } from '@prisma/client' const stripe = initStripe(process.env.STRIPE_SECRET_KEY) const prisma = new PrismaClient() module.exports = withApiAuthRequired(async (req, res) => { const { user: { email }} = getSession(req, res) const user = await prisma.user.findUnique({ where: { email }, }) await prisma.$disconnect() const session = await stripe.billingPortal.sessions.create({ customer: user.stripeId, return_url: process.env.CLIENT_URL, }) res.send({ url: session.url, }) }) ``` By allowing users to manage this stuff directly with Stripe, we do not need to build these flows ourselves, and since we have subscribed to those webhooks, Stripe will just let us know if the user changes anything. # Final thoughts It is amazing standing on the shoulders of giants! These services are incredible! We have created a complex SaaS project with authentication and multiple payment options with a very minimal amount of code. This stack was a pleasure to work in and was almost seamless. Stripe is not only making this stuff a delight for developers to build hobby projects, t hey are also enabling people of all kinds to set up their own online businesses and make a living. Very cool! # Helpful resources - [Build a SaaS project with Stripe](https://jonmeyers.io/blog/build-a-saas-platform-with-stripe) by me! - [React 2025](https://react2025.com/) by Lee Robinson - [Minimum viable SaaS](https://github.com/jaredpalmer/minimum-viable-saas) By Jared Palmer - [nextjs-auth0 repo](https://github.com/auth0/nextjs-auth0) - [Calling external API from Auth0 Rule](https://community.auth0.com/t/how-do-i-call-my-api-from-a-rule/41309) - [Rules metadata in Auth0](https://auth0.com/docs/rules/metadata) - [Calling a rule after social login](https://community.auth0.com/t/calling-hook-for-social-login/35604) - [Stripe API docs](https://stripe.com/docs/api) - [Stripe webhook verification with Next.js](https://codedaily.io/tutorials/Stripe-Webhook-Verification-with-NextJS) - [Testing Stripe webhooks](https://stripe.com/docs/webhooks/test) <EmailSubscribeWidget />
article
## Introduction You're about to start building a new website, and the first thing you do is run `create-react-app my-website` But have you ever stopped to consider why you're even using React in the first place? Is it just the hooks or the fact that you can easily create components and use them in pages? Why does this tool exist? This article will explain why React exists and how it has become a go-to tool as a fast way to create websites. ## A brief history of JavaScript React is a framework of JavaScript, so let's look at a brief history of JavaScript. Since 1993 when the first browsers ([Netscape Navigator](https://en.wikipedia.org/wiki/Netscape_Navigator)) with graphical user interfaces were invented, websites could only contain static content. No dynamic behavior like modals or lists of products pulled from an API, or dynamic events like today. Around 1995, there was that need to have some website interactions. And then, the Netscape team hired Brendan to create a scripting language for that purpose. That scripting language ended up being JavaScript! Over time, JavaScript has become the standard scripting language for websites. Chrome, Firefox, Internet Explorer and so on all have a JavaScript engine used to compile JavaScript code to perform those interactions. JavaScript works with [ECMAScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Language_Resources), which creates the standard by which all browsers should follow when creating JavaScript engines. ## What JavaScript does in the context of web development HTML and CSS are markup and stylesheet documents (respectively) that put elements together and style them to appear beautifully on a web page. But that's all they can do. You cannot trigger any dynamic content. This is where JavaScript comes in. JavaScript engines in web browsers also connect JavaScript and the web document built with HTML and CSS. Among many other features that the browsers allow JavaScript to do, the browsers also give JavaScript access to the [Document Object Model (DOM)](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model). The DOM is a tree object which contains all the elements in the web document. Access to this tree makes it possible for JavaScript to remove, modify, and add elements to the document. ## How we used to do it. How it's different now For example, we have a website with three pages: Home, About, and Contact. Here's an example of how this website would get created without the features of JavaScript: - `index.html` for the home page - `about.html` for the about page - `contact.html` for the contact page - `styles.css` for the stylesheets, which would contain style declarations for the app With a website like this, navigating to `mywebsite.com` would require the browser to request the path `/index.html` from the server. Depending on the network speed, or the availability of all the page's necessary resources, a response from the server may be delayed. If a user clicks on an **about** link on the homepage, the browser would again have to go through fetching the HTML file and loading the resources to the page. And the same thing goes for the contact page. There is always a site reload for any new navigation, even when the difference between page 1 and page 2 may be a single character or image. Single-Page Applications (SPAs) were introduced to solve this and other shortcomings. Websites today are faster, and with SPAs, debugging websites has also been made easier. ## The rise of single-page applications Multi-page Applications (MPA)--the traditional way of building applications—requires a page refresh on every navigation, even when the previous and current page contain minimal differences. The concept of SPAs involves dynamically composing elements and rendering the page on the client-side (which is the browser) for any page you navigate to. This is contrary to MPAs, which render the page from the server and only serve the resources for that page. Client-side rendering is accomplished with JavaScript. Most of this is done with the aid of DOM manipulations—modifying, adding, and removing elements on the screen--when a new page is activated. With SPAs, the website usually only reaches out to the server once to get an `index.html` file. The file references a JavaScript file that handles the client-side rendering implementation for different pages. So when you navigate to a new page, the page does not reload. The URL in the address bar is updated, the routing state in the browser is updated, and the JavaScript updates the document where needed. For places like the header and footer, which would usually be the same across all pages, those places are not re-rendered. Only the body content with new changes will be rendered. ## Front-end web development is extremely challenging The advancement of SPAs comes with more advanced challenges to developing for the front-end. Developers would now have to handle events, dynamically loading data, manually manage navigations, and more. Front-end isn't what it used to be. Imperitavily manipulating the DOM using JavaScript is a ton of work. Abstractions were needed. ## Declarative code can more predictable and easier to debug There are two programming paradigms which are **Imperative** and **Declarative** programming. In imperative programming, you tell the computer **the exact steps it needs to take to reach your desired result**. Declarative programming involves telling the computer **your desired results and letting it handle the steps**. A simple example to illustrate this is a filter operation. Let’s first see an imperative approach: ```js const arr = [1, 2, 3, 4, 5, 6, 7] const filtered = [] for(let i = 0; i++; i < arr.length) { const item = arr[i] if(item % 2 === 0) { filtered.push(item) } } ``` As you can see here, we’re telling the computer, step by step, the method in which we want to get what we want. Let’s look at something declarative: ```js const arr = [1, 2, 3, 4, 5, 6, 7] const filtered = arr.filter(item => item % 2 === 0) ``` Here you are telling the computer what you want, "Give me all the even numbers in this array". Of course, inside the higher-order function (`filter`), the implementation would be imperative. But from the abstraction, the step-by-step process is hidden. Declarative code is mostly abstractions that improve the readability of code. Also, they make code predictable. Looking at the imperative approach to filtering above, the function of those lines of code may not be easily predictable. `for` loops can do many things. But with the `filter` abstraction, you expect to get a filtered result just by the naming convention. And when code is easier to read and predict, it's easier to debug when something goes wrong. With JavaScript, any of these approaches are technically valid. But, as people keep building, abstraction upon abstraction is created to make code more declarative. You have libraries like lodash, jQuery, date formatting libraries, and many more. The same applies to the frameworks of today. We have a more declarative way of placing elements on web pages without having to use DOM manipulation methods like `[appendChild](https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild)` ## Declarative Code with Reusable Components The old way of building websites involved repeating common components (like header and footer) across all pages of the site. These components will usually have the same class names, all connected to one stylesheet to appear the same on every page. But this method makes it difficult to update these common components. Any additions to the header section on the home page would require a similar update to every `.html` file using the header. This method also makes testing a particular component more difficult because instead of testing it in just one place, you have to test it across every page. Today's Web applications are component-based, in the sense that they are built with the composition of standalone components. This method of building is made easier with the help of frameworks like React. You have your header, footer, and postcard component built individually and tested accordingly. Then, when creating your home page, you'd import your header and footer components like variables and build up your page using those components. Now instead of writing the same header implementation in all your pages, you'll have it in only one place and shared among all your pages. Apply a style change to the header, and the change gets reflected throughout the application. ## Where React came from, who writes and maintains it With the arising need for a more flexible, declarative, easy-to-maintain, and easier-to-control way of composing components and user interfaces, Facebook created. The prototype [which was called FaxJS](https://hackernoon.com/the-evolution-of-react-48409fac2efd) was created by Jordan Walker, a software engineer at Facebook. Many people write React today, from individual developers to frameworks like Gatsby and Next.js. React is used all around the tech ecosystem. As an open-source library, React has attracted many contributors who have added features, fixed bugs, and helped maintain and manage version updates. Check out the [React teams page](https://reactjs.org/community/team.html) for more information. ## Why it's popular and valuable in the current job market React is a desirable framework due to being backed by Facebook. Choosing a framework is a long-term investment for businesses, and they desire reliable long-term support for the tools they choose. React is also performant, scalable, flexible, and easy to maintain. It's a no-brainer why it's so appealing to enterprises. For developers, React is an attractive option for many reasons. It is well documented, easy to get started with, the community behind React is friendly, and many tools have been built for it. You have libraries for hooks, for state management, and many other things! <ArticleCourseCard course="the-beginner-s-guide-to-react"/> ## Conclusion Many developers initially jump into React because it makes it incredibly easy to get a website started, but as we've learned, it did a lot more than that. React is a powerful abstraction that allows us to write reusable, declarative components. Whereas before, we were writing static HTML pages, spending a lot of time manipulating the browser with imperative JavaScript code, or writing the same repetitive components across multiple files. We also learned what makes React appealing to businesses and why there is a market for React Developers. <Course slug="develop-accessible-web-apps-with-react" />
course
There are 1000s of plugins and themes in the Gatsby eco system, which is amazing but introduces the problem of deciding which to use to accomplish the feature you *actually* want to build. Analysis paralysis is real. Enter: Gatsbyjs Recipes Gatsbyjs Recipes are run from the CLI and automate common tasks like creating pages and layouts, installing and setting up plugins, adding a blog to a site, setting up Typescript, and many more. With the release of this new feature, Gatsby has created 11 official recipes that you can explore including: ThemeUI, Sass, Cypress, animated page transitions, and persistent layout components. In this collection, you will learn how to: - Set up Gatsby to use Recipes - Create a multi-step Recipe - Install NPM packages - Configure Gatsby Plugins - Create Custom files with Recipes
course
WordPress has been around for a long time and powers a huge number of sites. Just because WordPress isn't brand new doesn't mean it can't get the job done! Running WordPress as a Headless CMS gives you the benefit of a great content creation experience on the back end with the powerful Gutenberg editor while allowing you to use a modern JavaScript framework on the front-end. In this course, Kevin Cunningham will guide you through setting up WordPress as a headless CMS from scratch, as well as migrating from an existing WP site. You'll get practice with different WordPress content types, implement a GraphQL endpoint for querying data, and backup & deploy your site. All the while, you'll deepen your understanding of how headless WordPress approaches the relationship between content & rendering. Using WordPress as a headless CMS turns it into a datasource ready to work with Gatsby, Next.js, or whatever else you want to build with. Your and your clients will be able to take advantage of WordPress's content editing experience, without having to settle for a cookie-cutter theme on the frontend. With WordPress being decoupled from the rendered site, the database isn't hit for every request. This means faster performance and more security against WordPress exploits. You don't even have to host the editor at the same domain as the published site. ### While watching, consider... - What are the tradeoffs of using a CMS for a site? - Would headless WordPress work for me or my clients in this scenario?
course
This collection is a sequel to the [Building a Serverless JAMStack Todo app with Netlify, Gatsby, GraphQL, and FaunaDB](https://egghead.io/playlists/building-a-serverless-jamstack-todo-app-with-netlify-gatsby-graphql-and-faunadb-53bb) collection. In this collection we take the TODO application we built and convert it to run using Netlify Identity, AWS Lambda (using the serverless framework) and DynamoDB. We cover * Fauna vs DynamoDB and when to use each * Setting up AWS accounts * Creating DynamoDB tables and data modeling differences between Fauna and Dynamo * Converting our Netlify Functions deployment to a Serverless Framework deployment * Implementing Custom authorizer functions on AWS It uses tools that remove as many of the barriers as possible. Netlify Functions grows into Serverless Framework adn AWS Lambda, Netlify Identity is kept around, and FaunaDB can grows into DynamoDB.
course
On many websites, images and video make up the vast bulk of the data being sent over the wire; websites will often have _several megabytes_ of images! There's a lot of low-hanging fruit in this area. In this collection, we'll learn how to convert our images to the `webp` format—a format often **2-3x smaller** than png/jpg—and how to use the `picture` element to ensure graceful fallback on unsupported browsers. We'll see how to come up with a great abstraction for React to make it as painless to use as possible. Later in this collection, we'll also cover: - Automatically generating webp images on build - Leveraging `gatsby-image` to do the same thing in Gatsby - Smaller images across the browser spectrum with jpeg2000 and jpegxr - Avoiding layout problems with `display: contents` - Smaller video with `webm` instead of `mp4` Subscribe to make sure you don't miss it!
course
Gatsby’s `Link` component is a powerful way to improve the user experience and simplify the development workflow when building Gatsby sites. It makes navigating between internal links instantaneous, creating an app-like feel, and provides helpers for various common use cases. In this playlist, you’ll learn: - Why and how to use Gatsby’s `Link` component for internal link navigation - How to set styles for the currently active link - How to apply active styles to parent pages and other partially matching URLs - How to send state information in the props of the `Link` target - How to replace items in the navigation history - How to navigate programmatically using the `navigate` helper function
podcast
<p>Joel and Brian Lonsdorf discuss the pain and growth of learning, math as a source of truth, dispelling that idea that you need to be a wizard to enter the functional programming space, and finally how you can start including functional concepts in your day to day work.</p><p>There's a reason that mathematicians tend to be the best functional programmers. The theories and patterns directly apply, it has truth and purity. It's powerful, almost powerful enough to describe everything, so what makes people turn away from it?</p><p>Traditionally, math gets taught in a dry manner from a young age, tables are memorized, and facts get drilled. It isn't until much later that interesting concepts like set theory get introduced, and at that point, it's too late for many people.</p><p>Material that's "dry" doesn't have to be taught that way. It's been three and a half years since Brian first put Professor's Frisby's guide up on Github and it brought light and friendly perspective to heavy material. It showed that the functional programming paradigm was learnable without requiring a deep dive into Haskell.</p><p>The deep dive doesn't work for everyone. There's merit in starting with something like Gatsby and just getting something out there that you can play with immediately, and then later learn the fundamentals of Javascript. The same thing applies to learning functional programming. You can start composing with Lodash and ease into the deeper patterns and concepts.</p><hr /><h3>Transcript</h3><p><a href="https://egghead.simplecast.com/episodes/6d66e9e6/transcript">"Math and Functional Programming Aren't Exclusive to Wizards with Brian Lonsdorf" Transcript</a></p><h3>Resources:</h3><ul><li><a href="https://drboolean.gitbooks.io/mostly-adequate-guide-old/content/">Professor Frisby's Mostly Adequate Guide to Functional Programming</a></li><li><a href="https://egghead.io/courses/professor-frisby-introduces-composable-functional-javascript">Professor Frisby Introduces Composable Functional JavaScript</a></li><li><a href="https://hackernoon.com/function-composition-with-lodash-d30eb50153d1">Functional Composition with Lodash</a></li><li><a href="https://egghead.io/courses/state-monad-in-javascript">State Monad in JavaScript</a></li></ul><h3>Brian Lonsdorf:</h3><ul><li><a href="https://github.com/DrBoolean">Github</a></li><li><a href="https://twitter.com/drboolean?lang=en">Twitter</a></li><li><a href="https://medium.com/@drboolean">Medium</a></li></ul><h3>Joel Hooks:</h3><ul><li><a href="https://twitter.com/jhooks">Twitter</a></li><li><a href="https://joelhooks.com/">Website</a></li></ul>
lessonDuration 35m 42sFree
### **Have you authored a State Management library?** - Yes. Animation is entirely State. Moving from State to State in a fluid manner, dealing with interruptions. [Animated · React Native](https://reactnative.dev/docs/animated) - The Animated library is designed to make animations fluid, powerful, and painless to build and maintain. - Animated focuses on declarative relationships between inputs and outputs, configurable transforms in between, and start/stop methods to control time-based animation execution. - **The notion of physically-based animation.** - Physically-based animation is an area of interest within computer graphics concerned with the simulation of physically plausible behaviors at interactive rates. - Native applications are using "springs." Similar to a real springs (physically-based animation). It feels more real life, and it the way how iOS has implemented animations. - Problems occur when you need to apply this on the framework level. - If an animation is interrupted, it will result in a choppy animation. **This is due to JavaScript being single-threaded.** - The way native platforms are solving this problem is by moving this process to a different thread. - What we have done for Animated is that you define the animated values, then those values are sent to be computed in the dependency tree on a separate thread. - Now the challenge is how do you make declaring animations easier. ### **Is there a correlation between State and the *processes*? What layer of State is that?** - The difference between Animated and Recoil lies in how you update the DOM elements. - With Animated, we want to update the final DOM elements. - Recoil is a very low level of that implementation. You need to have find grain dependency management. - **Recoil works and thinks like React.** It uses the React component states and updates them. - The atomic unit that you are working on now is a React component. - You don't have to invent your own implementation. You can directly target specific React elements without reloading the entire tree. ### **What collaboration and resources came to inform this solution?** - Animated didn't inspire Recoil. The actual libraries are really small. The problem is how you educate people to start working with these libraries. ### These are complex problems. What are the common patterns when solving State Management? - **Recoil got inspiration from React Hooks.** - With Recoil, you are able to do the same thing as useState but also have access to a regular JavaScript object that you can pass around. - This has the benefit in that you no longer need to take over the whole JavaScript bundle. ### **What are the types of State that you have in an application?** - The first phase of State is the external data source that you get from the server. - For this type of State, Relay and GraphQL are excellent solutions. GraphQL is declarative. Relay handles local caching - transferring data between minor updates. And Relay is a superb solution to update specific components. ### **Why is Relay not the go-to solution?** - With Relay, you need to have a GraphQL backend. No easy way to create an integrated compatible backend solution. - At a conceptual level, we can think about Relay, GraphQL, and Apollo as the same, but at the implementation level, they differ from each other. - At the end of the day, the technology that you choose to work with will create constraints for your application. - **How you fetch data will affect the rest of your application.** - Gatsby uses a Relay-like implementation to build the Graph from 20-something data sources - but they make that invisible when building those structures. - Another type of website is CRUD apps that want more complex forms. There are no good solutions to manage forms. In the past, Redux was used, but it didn't solve the problem. - PHP, Rails, WordPress let you generate forms and manage them nicely on the backend. - Recoil solved problems for Formik. Managing states and updates in nested forms. [Jared Palmer and Joel talk about State Management](https://www.notion.so/egghead/Jared-Palmer-and-Joel-talk-about-State-Management-20676ba02a8b4484912e3b59d77c742c) ### **Have you ever explored Falcore?** - Yes. Falcor is a real-time rendering framework supporting DirectX 12. It aims to improve the productivity of research and prototype projects. [NVIDIAGameWorks/Falcor](https://github.com/nvidiagameworks/falcor) - The idea with Falcor is that we can do the same thing without having a solid schema (Dynamically importing REST points.) - This solves the same issues when managing State, and it lowers the barrier of entry. ### **What State Management problems did you run into when building Excalidraw?** [Excalidraw](https://excalidraw.com/) - The initial plan was to use Recoil. The solution was to create one JSON file to manage the state. Then re-render the whole tree. - It worked pretty well until we wanted to update different parts at different rates. We wanted the interaction to be faster and making caching easier. - Recoil would have handled this for us, but we took a different approach; we started building tooling with pure React and JavaScript. - We didn't want to add additional features that would make it slower. - We implemented the core features from other libraries to avoid adding additional dependencies. - This is a design feature; you can start designing backward. - **Optimizing** - At WhatsApp, we optimize by writing small amounts of code and adding little to no dependencies. - Facebook takes a different approach. They iterate fast, so they are implemented in multiple libraries. - **Both are successful but with different strategies.** ### **When you are doing optimization at scale, is State Management part of that?** - State Management is part of the conversation. But it's not critical since this is not likely to change much. - For example, when we re-wrote Facebook from PHP to React + GraphQL + and server-side rendering. The underlying architecture did not change much. - **To improve the performance, you need to measure it**. - Our team has focused on measuring performance in testing, production, etc. Once we have those measurements, we can start implementing tools to track performance. - Many teams own different parts of Facebook. We take all of those metrics and put them in a program where executives can review the status. - **It's State Management at a business level. Everything is moving-different components.** - If you give a Metric to an engineer, they will drive it down. They are excited to make it fast. It's important to track it. If you want to improve performance, you need to track it, improve it, and show it to management.
lessonDuration 1h 22mFree
Joel and Mark Erikson chat about the motivation behind Redux. The historical context and the future of Redux. How Redux Toolkit solves community pain points. Additionally, Mark Erikson gives a walkthrough of how Redux Toolkit works and how to use createSlice, createAsyncThunk, and createEntityAdapter. ## Key Terms **Redux** - Redux is an open-source JavaScript library for managing application state. **Immer** - a library created based on the “copy-on-write” mechanism — a technique used to implement a copy operation in on modifiable resources. **Flux** - is an architecture for creating data layers in JavaScript applications. It was designed at Facebook along with the React library. **Redux Toolkit** - an add-on package to Redux, which includes opinionated defaults. ## Resources - [https://twitter.com/acemarke](https://twitter.com/acemarke) - [Redux Toolkit](https://redux-toolkit.js.org) - [Mark's Dev Blog](https://blog.isquaredsoftware.com) - [Redux - A predictable state container for JavaScript apps](https://redux.js.org) ## What keeps you excited about Redux? - The motivation: people are still using Redux and will continue to use Redux for a long time. ## How do people criticize Redux? - This blog post was a result of responding to the endless waves of “Redux is dead...” - People don’t understand the context and history behind why a particular tool exists—for example, jQuery, Angular, Backbone, etc. - All these tools were created at a specific time, in a particular place, by people trying to solve particular problems. - And they were written using the knowledge that existed at that particular time. - Understanding the context will help you know where it belongs in the larger picture. - **Example of this:** "Things You Should Never Do, Part I" by Joel Spolsky. “When you throw away code and start from scratch, **you are throwing away all that knowledge**. All those collected bug fixes. Years of programming work.” ## Redux in 2020 - In the **context of Redux**, it came out in 2015. And currently, people ask: - Why do I have to dispatch things? - Why is it called actions? - Why do I need to have separation between data and UI? - Here, it’s essential to understand that Flux inspired Redux. - Like Flux, Redux prescribes that you concentrate your model update logic in a particular layer of your application. Instead of letting the application code directly mutate the data, both tell you to describe every mutation as a plain object called an “action.” - The idea was to have access to a single function and not worry about synchronization. - People learning Redux today don’t see the historical context of those patterns. - **Another criticism of Redux:** verbosity. - The reality is that Redux lets us choose how verbose we’d like your code to be, depending on personal style, team preferences, longer-term maintainability, and so on. - The **three fundamental principles** of Redux has been over-interpreted: - **Single source of truth**: The state of your whole application is stored in an object tree inside a single store. - **State is read-only**: The only way to mutate the state is to emit an action, an object describing what happened. - **Mutations are written as pure functions**: To specify how the state tree is transformed by actions, you write pure reducers. ## Redux Toolkit - People have assumed that they need to put everything into Redux. But that’s overkilled. It’s quickly going to become unmaintainable. - Link to doc: [When should I use Redux?](https://redux.js.org/faq/general#when-should-i-use-redux) - The approach to dealing with Boilerplate in Redux was to use Immer. - **Michel Weststrate** builds Immer - simplifies writing immutable update logic: [Docs:](https://immerjs.github.io/immer/docs/introduction) “The basic idea is that you will apply all your changes to a temporary draftState, which is a proxy of the currentState. Once all your mutations are completed, Immer will produce the nextState based on the mutations to the draft state.” [Michel Weststrate creator of Mobx and Immer Libraries for JavaScript](https://egghead.io/podcasts/michel-weststrate-creator-of-mobx-and-immer-libraries-for-javascript) - Putting everything together changed how Redux Toolkit was created. It addressed three common concerns about Redux: 1. “Configuring a Redux store is too complicated.” 2. “I have to add a lot of packages to get Redux to do anything useful.” 3. “Redux requires too much boilerplate code.” - Redux Toolkit was built to be beneficial to all Redux users, not just someone new to Redux. - It’s very opinionated. ## What are the big ideas of State Management? - First, ask yourself, what type of app am I building? - Where is the data coming in from? - How am I interacting with that data? - How long does the data need to live? - Does the data need to change over time? - Those questions will dictate what tools to use. - An **example** of this: Building a MEAN.js AngularJS Project with Create-React-App. ## What does the future look like for Redux? - "Redux is here to stay..." - Many downloads are coming from Wordpress’s Gutenberg (block editor) and other larger projects such as Gatsby. During Gatsby’s bootstrap & build phases, the state is stored and manipulated using the Redux library. The fundamental purpose of using Redux in Gatsby’s internals is to centralize all of the state logic. - Lots of tools overlap with Redux. It has passed the peak of popularity, and usage will shrink over time. But at the same time, people are going to keep using Redux. Technologies don’t just disappear. - **Questions to be answered:** - How will Redux fit with Concurrent Mode and other features from the React team? - Redux will probably make use of `useMutableSource` for compatibility purposes. [useMutableSource](https://github.com/facebook/react/pull/18000) - enables React components to safely and efficiently read from an unreliable external source in Concurrent Mode. The API will detect mutations that occur during render to avoid tearing, and it will automatically schedule updates when the source is mutated. ## Redux Toolkit The recommended way to start new apps with React and Redux Toolkit is by using the official Redux+JS template for Create React App. - The first problem that it’s trying to solve: it takes too many steps to set up a store. - The solution is to create Reducers that specify how the application’s state changes in response to actions sent to the store. - Actions only describe what happened but don’t explain how the application’s state changes. - With Flux, they had individual stores. In Redux, you have a single Object decided up. - It’s generally agreed that functions should be relatively short and ideally only do one specific thing. - One key/value section of that object is a “slice,” We use the term “slice reducer” to describe the reducer function responsible for updating that slice of the state. ### Structure files as "Ducks": - Redux itself does not care about how your application’s folders and files are structured. However, co-locating logic for a given feature in one place makes it easier to maintain that code. - Redux Toolkit addressed a pain point from the community: having several files for one feature. ## Working with `createSlice` As `createSlice` creates your actions and your reducer for you, you don’t have to worry about type safety here. Action types can just be provided inline. ## Working with `createAsyncThunk` - This API focuses on creating a standard recommended approach for handling async request lifecycles. Link to documentation of `createAsyncThunk`: - If you need to cancel a `thunk` before the payload creator is called, you may provide a condition callback as an option after the payload creator. ## Working with `createEntityAdapter` - It provides a set of functions that handles the “entity state” structure. - This API was ported from the `@ngrx/entity library` created by the NgRx maintainers and significantly modified for Redux Toolkit. - You can decide what `actions` to pass. And the CRUD methods may be used in multiple ways. ## Pull Request #3740 - The Redux documentation needs to be re-written. The current documentation was written in 2015; it’s no longer relevant for new developers. - **The Master List.** - Goals: - Just Enough of Redux. - Learn the basics of Redux and the fastest way to get going, + “the right way.” - Show enough real-world patterns that you can build an app. ## Instructional Design - Egghead has focused on taking subject matter experts and systematically designing, developing, and delivering instructional products. - The outputs can be a video course, documentation, etc.; what’s important is the output. - There is no downside to having an instructional design session on the Redux documentation. ## Roam Research - Roam as a tool for networked thought. - Powered by bi-directional links. ## Redux Toolkit 1.0 "Redux is not designed to be the most performant or the most concise way of writing mutations. Its focus is on making the code predictable." - **Tradeoffs of React Hooks:** [https://www.youtube.com/watch?v=xiKMbmDv-Vw&feature=youtu.be](https://www.youtube.com/watch?v=xiKMbmDv-Vw&feature=youtu.be) **Recap:** It's about tradeoffs. Neither approach is "right" or "wrong" - it's about what tradeoffs you want to make: - How much do you want to "separate concerns"? - Do you prefer "shallow" testing of components, or fully "mounting/integrating" them? - How important are shallow component trees and static typing? [Source to Slides.](https://blog.isquaredsoftware.com/presentations/2019-09-hooks-hocs-tradeoffs/#/16)
lessonDuration 2m 1s
Netlify will automatically build your Gatsby website whenever you push new code to your repository but what about content changes in Contentful. In this lesson, you will learn how to use Contentful webhook feature to trigger a Netlify build whenever you publish or delete new content on Contentful
lessonDuration 3m
In this lesson, you will learn how to use the Graphql backreferences created by Gatsby to get more data from a parent content type. In this example, we have a lesson that references an instructor but the instructor content type does not have any data about the lessons that are assigned to it. Usually, you would create a reference back in the instructor content type to the lesson but this can cause a circular reference that's hard to maintain. Fortunately in the Gatsby data layer, GraphQL, we can query the parent node to get its data from its child. That's called backreference.
lessonDuration 3m 20sFree
Gatsby provides a React hook that lets us use static queries in our components. It's called (appropriately) `useStaticQuery`. In this lesson, you'll learn how to use `useStaticQuery` to get site metadata from your Gatsby config file.
lessonDuration 2m 13sFree
Because WPGraphQL already provides a GraphQL API, we can access it directly in Gatsby using `gatsby-source-graphql`. In this video, we’ll install and configure the plugin in Gatsby so we can see WordPress data loaded in Gatsby’s data layer.
lessonDuration 4m 25s
Heavy duty CLI's like gatsby and npm do more than one thing. The convention is to namespace them with a command name after the CLI name, like `gatsby new` or `gatsby build` or `npm install` or `npm uninstall`. We should be comfortable converting our single purpose CLI's into multi command CLI's as our needs grow, as well as understand how to share logic between commands to keep code DRY.
lessonDuration 4m 11sFree
In this lesson you will learn how to increase performance of the images used in your website built with Gatsby.js. Img component provided by Gatsby enables lazy loading, applies cool visual effects on image loads and is virtually everything you need to comfortably work with images.
lessonDuration 1m 54sFree
In this lesson, you'll learn how to use Gatsby's GraphQL explorer GraphiQL in order to query your data. We'll walk through starting up the Gatsby development server which starts up GraphiQL and how to use it to make a basic query, explore custom Pokemon data sourced in Gatsby, and generate a code snippet of that query to use in our app.