Next.js & Contentful Site Build Tutorial #7 - Generating Paths

Net Ninja · Beginner ·🌐 Frontend Engineering ·5y ago

Key Takeaways

Generates static pages for recipe routes using getStaticPaths in a Next.js application with Contentful

Full Transcript

all right gang so now we have our recipes listed here and when we click on one we go to a new page using that recipes slug in the path so this page is being driven by the slug components over here this thing right here this is what we see because this file and file path matches the route we go to but we need to generate the static pages for these routes so that when we visit one each one shows its own data for that recipe so if i'm on this one it shows the recipe for my my potatoes if i go to this one it shows the recipe for the marmite skewers etc now the way we do this in next js is to use the get static paths function inside the slug components now if you're unfamiliar with this then definitely check out my next js crash course first where i talk about this function in detail the link is going to be down below but basically this function is responsible for finding out all of the paths or routes which will use this component as its page and then next js can generate a static page for each one of those paths at build time right so to do this we basically need to find out the slog of every recipe we have in contentful because they will be the paths for each of the pages generated so the first thing we need to do is start to communicate with contentful now in order to do that we need the contentful clients now we do that over here inside the index file so i'm just going to copy this stuff from here so we can use it inside this log file as well so first of all the import statement at the top and then also i'm going to grab this thing right here where we use the create client function and we grab the environment variables we need to connect to it so let me copy this dude and paste it over here now this time around i'm not pasting this inside a function over here we pasted it inside get static props because in this component in this page this is the only place it's going to be used inside this function but in this component we're going to be using it in two separate functions and we'll see that shortly so i don't want to place this inside one of those functions because then it's only scoped to that function and we can't use it in both then so i'm creating it at the top level outside of both functions first of all now we need to create the get static paths function so i'm going to say const and then get static paths and set that equal to an async function then inside here this is where we're going to use this client to get all of the entries and find out the slug for each one so that next js can generate a static page for each one we also need to export this so we'll say export in front of it all right then so first of all let's get all of the entries using this so i'll say const response is equal to a weight and then it's the clients dot get entries like so and remember we need to pass in an object with some options or rather just one single option here to say what content type do we want to get so we want to get the recipes content underscore type and set that equal to recipe that is the id of the content type that we want to get so this gets us all of the items all of the recipes and it stores them inside an item's property on this response right here now ultimately down here we need to return an object right and inside this object we need to return a paths property now the value of this should be an array of path objects so a lot of different objects like this this is what next js will use to build our static pages for each path so the array of objects are going to look a little bit like this we'll have each object have a params property then that will also be an object and inside here we're going to have a slug property and that is going to be the slog of each item that we get now it looks a little bit complex right but we have an array of these different path objects so there'll be several of these one for each recipe and in each one of those objects we have a params property to specify any route parameters for that path we only have one route parameter in our paths and that is the slog so we have a slog property in this object where we say what the slog is of each item so this is ultimately what we want to return now in order to do this in order to generate this array i'm going to use the map method on the items that we get back on this response right here so i'll say const paths is equal to response dot items dot map now inside here we fire a function for each one and we get access to that individual item now we want to return an object for each one and then that object will be placed in an array stored in paths so the object remember looks like the objects we had down here where inside this we have a params property which is also an object and we specify the slog parameter and we can get that from item dot fields dot slug all right so now here we have that array and we can just apply it down here so this now is gonna work now next js is gonna know all of the different paths it needs to generate and all of the different static pages for each path now because this name and this name are the same we can shorten this so it's just paths and then this automatically uses this value all right so we have the paths property now we also need to return one other thing and that is a fallback property and that is going to be set to false now this basically means if we go to a path that doesn't exist in these paths right here we'll show a 404 page instead of a fallback page now we're going to talk more about this later on in detail when we implement fallback pages and incremental static regeneration but for now let's just set this to false meaning if they go to a slug or a path that doesn't exist so forward slash recipes forward slash abc which doesn't exist then we're going to show a 404 page instead of a fallback page all right then so now we're returning this array of paths right here next knows to create a page based on this component right here for each of those paths or routes so now we'll have a page for each recipe but we also need to access the data for each individual page now to do this we need to use the get static props function for this component much like we used it for this index component over here so let me just grab this thing i'm going to copy it and come over here and i'm going to paste it right here now i'm going to get rid of all of the stuff inside of it because i don't want that we're going to flesh this out from scratch so again we need to use this contentful client right here to interact with contentful so again get the item the single item this time that we need now you might be thinking well we've already got all of the items right here well yeah but this is done at build time right and we make this fetch request to get the items so that we can generate the paths this thing right here is to fetch a single item based on the page that we're on and that item then is gonna be injected as a prop right here so we do have to make these separate fetches so first of all i'm going to say const response is equal to a weight client and then dot get entries like so now inside here again we need to specify the content underscore type and that is going to be recipe now this right here is going to get all of the recipe entries and we don't want to do that we just want to get a single one but how do we know which one well after next js runs this right here it generates those different paths and pages and for each one of those different paths it runs this function so it's going to run it in our case four different times and each time it runs it it passes in a context object and on that context object there is a params property and that params property is going to contain the slug because it's just this object right here so params.slog is going to give us the actual slog of that particular recipe that this is running for and we can use that slog to limit this request to just get the item with that slug property so instead of accepting context i'm going to destructure the params property from that context object and that is just going to be this object right here so i can access the slog on this now so to only get a single recipe based on the value of a field we add in a second property right here and this time it's going to be in quotes and we want to say fields dots slog or whatever field we want to match now we want to match to the slog and it's going to be params.slug so this is how we can kind of limit what we get back from contentful we can say we want the slug or any other field to match this value now if multiple entries match that value it's going to retrieve all of those but we know that the slug field is unique so it's only going to get one now this still returns an array so response to items is going to be an array and in fact we can just destructure items from the response right here if you want to that's fine as well so it's going to be an array even though there's only one item inside it because it doesn't know at this point there's only going to be one item it might be several so it always returns an array so we have to remember that now down here we need to return an object so we can inject the props into the component so props is going to be an object where we have a recipe prop that we want to inject and that is going to be items but we just want the item inside that the first item so zero and that means we're not passing in an array as a prop into this now we're just passing in a single item object the first item inside this array okay so now we could destructure that from the props right here recipe like so and all i'm going to do for now is log that recipe to the console like so save it and refresh over here so you can see we're on veggie marmite skewers if i inspect right now and go to the console we see we have this single object this single recipe and we can see it is the veggie marmite skewers if i go home i'm going to clear this and then choose a different one like cheesy marmite toast so let's go there open this up and we can see now we have the cheesy marmite toast so now we have that inside our component we can go ahead and output the data from this recipe inside the template and we're going to do that next

Original Description

🐱‍💻 🐱‍💻 Course Files: + https://github.com/iamshaunjp/next-contentful 🐱‍👤🐱‍👤 JOIN THE GANG - https://www.youtube.com/channel/UCW5YeuERMmlnqo4oq8vwUpg/join 🐱‍💻 🐱‍💻 My Udemy Courses: + Modern JavaScript - https://www.thenetninja.co.uk/udemy/modern-javascript + Vue JS 3 & Firebase - https://www.thenetninja.co.uk/udemy/vue-and-firebase + D3.js & Firebase - https://www.thenetninja.co.uk/udemy/d3-and-firebase 🐱‍💻 🐱‍💻 Useful playlists: + Next.js Tutorial for Beginners - https://www.youtube.com/watch?v=A63UxsQsEbU&list=PL4cUxeGkcC9g9gP2onazU5-2M-AzA8eBw + Full React tutorial - https://www.youtube.com/watch?v=j942wKiXFu8&list=PL4cUxeGkcC9gZD-Tvwfod2gaISzfRiP9d 🐱‍💻 🐱‍💻 Other links: + Get VS Code - https://code.visualstudio.com/ 🐱‍💻 🐱‍💻 Social Links: Facebook - https://www.facebook.com/thenetninjauk Twitter - https://twitter.com/thenetninjauk Instagram - https://www.instagram.com/thenetninja/
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Net Ninja · Net Ninja · 0 of 60

← Previous Next →
1 Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Net Ninja
2 Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Net Ninja
3 Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Net Ninja
4 GraphQL Tutorial #1 - Introduction to GraphQL
GraphQL Tutorial #1 - Introduction to GraphQL
Net Ninja
5 GraphQL Tutorial #2 - A Birdseye View of GraphQL
GraphQL Tutorial #2 - A Birdseye View of GraphQL
Net Ninja
6 GraphQL Tutorial #3 - Project (stack) Overview
GraphQL Tutorial #3 - Project (stack) Overview
Net Ninja
7 GraphQL Tutorial #4 - Making Queries (front-end preview)
GraphQL Tutorial #4 - Making Queries (front-end preview)
Net Ninja
8 GraphQL Tutorial #5 - Express App Setup
GraphQL Tutorial #5 - Express App Setup
Net Ninja
9 GraphQL Tutorial #6 - Setting up GraphQL
GraphQL Tutorial #6 - Setting up GraphQL
Net Ninja
10 GraphQL Tutorial #7 - GraphQL Schema
GraphQL Tutorial #7 - GraphQL Schema
Net Ninja
11 GraphQL Tutorial #8 - Root Query
GraphQL Tutorial #8 - Root Query
Net Ninja
12 GraphQL Tutorial #9 - The Resolve Function
GraphQL Tutorial #9 - The Resolve Function
Net Ninja
13 GraphQL Tutorial #10 - Testing Queries in Graphiql
GraphQL Tutorial #10 - Testing Queries in Graphiql
Net Ninja
14 GraphQL Tutorial #11 - GraphQL ID Type
GraphQL Tutorial #11 - GraphQL ID Type
Net Ninja
15 GraphQL Tutorial #12 - Author Type
GraphQL Tutorial #12 - Author Type
Net Ninja
16 GraphQL Tutorial #13 - Type Relations
GraphQL Tutorial #13 - Type Relations
Net Ninja
17 GraphQL Tutorial #14 - GraphQL Lists
GraphQL Tutorial #14 - GraphQL Lists
Net Ninja
18 GraphQL Tutorial #15 - More on Root Queries
GraphQL Tutorial #15 - More on Root Queries
Net Ninja
19 GraphQL Tutorial #16 - Connecting to mLab
GraphQL Tutorial #16 - Connecting to mLab
Net Ninja
20 GraphQL Tutorial #17 - Mongoose Models
GraphQL Tutorial #17 - Mongoose Models
Net Ninja
21 GraphQL Tutorial #18 - Mutations
GraphQL Tutorial #18 - Mutations
Net Ninja
22 GraphQL Tutorial #19 - More on Mutations
GraphQL Tutorial #19 - More on Mutations
Net Ninja
23 GraphQL Tutorial #20 - Updating the Resolve Functions
GraphQL Tutorial #20 - Updating the Resolve Functions
Net Ninja
24 GraphQL Tutorial #21 - GraphQL NonNull
GraphQL Tutorial #21 - GraphQL NonNull
Net Ninja
25 GraphQL Tutorial #22 - Adding a Front-end
GraphQL Tutorial #22 - Adding a Front-end
Net Ninja
26 GraphQL Tutorial #23 - Create React App
GraphQL Tutorial #23 - Create React App
Net Ninja
27 GraphQL Tutorial #24 - Book List Component
GraphQL Tutorial #24 - Book List Component
Net Ninja
28 GraphQL Tutorial #25 - Apollo Client Setup
GraphQL Tutorial #25 - Apollo Client Setup
Net Ninja
29 GraphQL Tutorial #26 - Making Queries from React
GraphQL Tutorial #26 - Making Queries from React
Net Ninja
30 GraphQL Tutorial #27 - Rendering Data in a Component
GraphQL Tutorial #27 - Rendering Data in a Component
Net Ninja
31 GraphQL Tutorial #28 - Add Book Component
GraphQL Tutorial #28 - Add Book Component
Net Ninja
32 GraphQL Tutorial #29 - External Query File
GraphQL Tutorial #29 - External Query File
Net Ninja
33 GraphQL Tutorial #30 - Updating Component State
GraphQL Tutorial #30 - Updating Component State
Net Ninja
34 GraphQL Tutorial #31 - Composing Queries
GraphQL Tutorial #31 - Composing Queries
Net Ninja
35 GraphQL Tutorial #32 - query variables
GraphQL Tutorial #32 - query variables
Net Ninja
36 GraphQL Tutorial #33 - Re-fetching Queries
GraphQL Tutorial #33 - Re-fetching Queries
Net Ninja
37 GraphQL Tutorial #34 - Book Details Component
GraphQL Tutorial #34 - Book Details Component
Net Ninja
38 GraphQL Tutorial #36 - Styling the App
GraphQL Tutorial #36 - Styling the App
Net Ninja
39 GraphQL Tutorial #35 - Making a Single Query
GraphQL Tutorial #35 - Making a Single Query
Net Ninja
40 Build Apps with Vue & Firebase - Udemy Course
Build Apps with Vue & Firebase - Udemy Course
Net Ninja
41 Updated Vue & Firebase Course (Udemy)
Updated Vue & Firebase Course (Udemy)
Net Ninja
42 Vue & Firebase Real-time Chat (Preview) #1 - Intro
Vue & Firebase Real-time Chat (Preview) #1 - Intro
Net Ninja
43 Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Net Ninja
44 Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Net Ninja
45 Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Net Ninja
46 Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Net Ninja
47 Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Net Ninja
48 Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Net Ninja
49 Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Net Ninja
50 Object Oriented JavaScript Tutorial #1 - Introduction
Object Oriented JavaScript Tutorial #1 - Introduction
Net Ninja
51 Object Oriented JavaScript Tutorial #2 - Object Literals
Object Oriented JavaScript Tutorial #2 - Object Literals
Net Ninja
52 Object Oriented JavaScript Tutorial #3 - Updating Properties
Object Oriented JavaScript Tutorial #3 - Updating Properties
Net Ninja
53 Object Oriented JavaScript Tutorial #4 - Classes
Object Oriented JavaScript Tutorial #4 - Classes
Net Ninja
54 Object Oriented JavaScript Tutorial #5  - Class Constructors
Object Oriented JavaScript Tutorial #5 - Class Constructors
Net Ninja
55 Object Oriented JavaScript Tutorial #6 - Class Methods
Object Oriented JavaScript Tutorial #6 - Class Methods
Net Ninja
56 Object Oriented JavaScript Tutorial #7 - Method Chaining
Object Oriented JavaScript Tutorial #7 - Method Chaining
Net Ninja
57 Object Oriented JavaScript Tutorial #8 - Class Inheritance
Object Oriented JavaScript Tutorial #8 - Class Inheritance
Net Ninja
58 Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Net Ninja
59 Object Oriented JavaScript Tutorial #10 - Prototype
Object Oriented JavaScript Tutorial #10 - Prototype
Net Ninja
60 Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Net Ninja

Related Reads

📰
I Built 174 Free Browser-Based Tools Using React + Vite
Learn how to build a suite of free browser-based tools using React and Vite, and why this matters for developers and users alike
Dev.to · Utkarsh Bharti
📰
How I Merge PDFs in the Browser with Vue 3 and pdf-lib
Learn to merge PDFs in the browser using Vue 3 and pdf-lib, streamlining document management and reducing server load
Dev.to · sunshey
📰
Trying Declarative Partial Updates: A Future API for Replacing HTML Later
Learn about Declarative Partial Updates, a potential future API for replacing HTML, and how it can improve frontend development
Dev.to · nyaomaru
📰
Debugging React: From Taking a Deep Breath to Finding the Root Cause
Learn to debug React applications by taking a systematic approach to identify and fix issues
Dev.to · surajrkhonde
Up next
The masks we wear | Zora Krstić | TEDxLuxembourgCity
TEDx Talks
Watch →