Swizec Teller - a geek with a hatswizec.com

Senior Mindset Book

Get promoted, earn a bigger salary, work for top companies

Senior Engineer Mindset cover
Learn more

    Exploring NextJS with a headless CMS, pt4 – CodeWithSwiz

    getStaticProps, environment vars, and why you shouldn't use yarn link – all in this episode of #CodeWithSwiz

    CodeWithSwiz is a twice-a-week live show. Like a podcast with video and fun hacking. Focused on experiments. Join live Wednesdays and Sundays

    This was a fantastic streaming session. The thing works! You can do what I've been trying to build for the past 3 episodes 🤘

    Paste markdown into the new Markdown pasta 🍝 textarea and your article transforms into a full preview.

    • youtube links turn into thumbnails
    • tweets turn into screenshots
    • code goes through carbon.now.sh
    • twitter names turn into links
    • gifs are embedded

    Check it out live on swiz-cms.vercel.app

    Preview of markdown machinery
    Cryptic error about React hooks
    Cryptic error about React hooks

    Much of our frustration budget was spent on this cryptic error. "Naughty naughty, calling hooks in a class component"

    You get this error when using yarn link to develop libraries. Like when you have a piece of code you want to re-use in different projects.

    Library development relies on a combination of unit testing and integrating with your target project. I skip unit testing on stream because lazy ✌️

    You end up testing through integration.

    Best way to do that is to yarn link (or npm link) a local project into your code. That way changes are reflected immediately.

    And it leads to having multiple instances of React in the same project. One from your project, one from your library. Running instances in the browser that is. Happens with Vue too.

    You have to publish your library for every change 😩

    1. see bug
    2. make change and pepper console logs
    3. yarn build
    4. git commit
    5. npm version patch
    6. npm publish
    7. change to target project
    8. yarn add library

    For every change. Yeah it sucks. You learn to maximize debugging info for every change.

    Environment variables

    Environment variables are best used for configuring your API keys and other secrets. You shouldn't hardcode those and they shouldn't be part of your repository.

    NextJS has fantastic support out of the box. We kinda guessed on stream and it worked 🤘

    For local development, create a .env.local file. Do not add to git

    // /.env.local GIPHY_API_KEY=value

    You can then read these variables on the server and during builds with process.env.GIPHY_API_KEY.

    They're hidden from the browser for security reasons.

    For production and preview secrets, you should use Vercel's or Netlify's UI. They keep secrets encrypted and out of your codebase. Like it should be.

    Prod, preview, dev secrets in Vercel
    Prod, preview, dev secrets in Vercel

    getStaticProps

    Having env vars on the server and inside builds is great, but our <LetterBuilder> plugin needed them in the browser.

    You can expose public vars in NextJS by prefixing with NEXT_PUBLIC. I haven't tried if that works on Netlify.

    Our API key isn't public though. It's a true secret and should stay secret. You can see it on my stream because I'm a terrible person. And because I can click a button to change it 😉

    We used getStaticProps to read the key at build time and send it to our page as a React prop. This is insecure.

    // /pages/index.js
    
    export async function getStaticProps() {
        return {
            // populate props however you want
            props: {
                giphyAPIKey: process.env.GIPHY_API_KEY,
            },
        };
    }
    
    // ...
    
    export default function Home({ giphyAPIKey }) {
    

    When you export getStaticProps from your page, NextJS runs your method when building the page. Either for static rendering or their static generation magic.

    Those props are then baked into the render of your exported default component.

    Similar to Gatsby's staticQuery and useStaticQuery without the complication of GraphQL and far more flexible. You can use this method for anything you want. Even API requests.

    Make sure your props are serializable JSON ✌️

    Cheers,
    ~Swizec

    Published on September 10th, 2020 in CodeWithSwiz, Livecoding, Technical

    Did you enjoy this article?

    Continue reading about Exploring NextJS with a headless CMS, pt4 – CodeWithSwiz

    Semantically similar articles hand-picked by GPT-4

    Senior Mindset Book

    Get promoted, earn a bigger salary, work for top companies

    Learn more

    Have a burning question that you think I can answer? Hit me up on twitter and I'll do my best.

    Who am I and who do I help? I'm Swizec Teller and I turn coders into engineers with "Raw and honest from the heart!" writing. No bullshit. Real insights into the career and skills of a modern software engineer.

    Want to become a true senior engineer? Take ownership, have autonomy, and be a force multiplier on your team. The Senior Engineer Mindset ebook can help 👉 swizec.com/senior-mindset. These are the shifts in mindset that unlocked my career.

    Curious about Serverless and the modern backend? Check out Serverless Handbook, for frontend engineers 👉 ServerlessHandbook.dev

    Want to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz React components your whole team can understand with React for Data Visualization

    Want to get my best emails on JavaScript, React, Serverless, Fullstack Web, or Indie Hacking? Check out swizec.com/collections

    Did someone amazing share this letter with you? Wonderful! You can sign up for my weekly letters for software engineers on their path to greatness, here: swizec.com/blog

    Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

    By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️

    Created by Swizec with ❤️