Next.js & Identity (auth) Tutorial #9 - Netlify Functions with Identity
Key Takeaways
Integrates Netlify Functions with Netlify Identity for authentication
Full Transcript
all right then so now we've created our first netlify function right here super mario and recall that from the guides component right here and we just log out the data to the console and we can do all of this locally because we installed the netlife cli to run netlifedev and get that proxy server that allows us to run these functions locally before even deploying them so all this is working but remember the whole point of us using these netlife functions is to protect some data from unauthenticated users in our case we want to use a function to send back some guides to the front end but only if that user is logged in if they're not we don't want to send it back so if i go to the guides page and i'm logged in then the function sends all of that data back so we can show it on this page if i'm not logged in we'll send back maybe some kind of error or something else instead so we need a way to authenticate requests when they come into a function like this unfortunately netlify makes that pretty easy to do so when a request is made to a netlife function netlify can determine if that request was made from a logged in user and it does this by looking for the presence of a valid user access token on the request if it's there the user is logged in if it's not they're not logged in so let's try this out with a brand new function so let's create that function inside the functions folder i'm going to call it guides because that's what we're getting right some guides oops not spelled that correctly let's rename that to guides instead of guide and then inside here we'll create the function so exports dot handler we set that equal to an async function now inside this function we're going to take in two arguments automatically the event and context now we'll talk more about that later on and in particular we're going to talk about this context object which is the context of the request this is how we're going to determine whether a user is logged in but again we'll talk about that later now what i'm going to do is just paste in a bit of data right here so i have a constant called guides and i set that equal to an array of object where each object is a guide so it has a title and an author so this is the data we're going to send back now in a real application you wouldn't just hard code this data here probably you probably have it in a database somewhere communicate with the database and grab that data but for the sake of this tutorial i want to keep the focus on identity and functions and i don't want to introduce too much like a database but maybe in the future i will do something with that anyway we have this guide's data and this is ultimately what we want to return to the user so what i'm going to do is say right here return we return an object where the status code is going to be 200 meaning everything is okay with the request and then the body is going to be the data but we have to stringify it so jason dot stringify and then we pass in the guides okay so this is just a simple function a bit like before we're just returning a bit of data the guides so before we add in any extra logic to check the authentication of the user let's go and request this function from our guides page so the only real thing we need to do right here is just change the end point of this function so instead of it being super mario it's going to be guides like so now when i do that i'm gonna restart the server so if i go over here i'm gonna control c to exit this process then i'm gonna run netlifedev again just because i've added a new function and i want it to pick up that function and uh so we can access it using this server so once i've done that i'm going to come over here and i'm going to refresh this page i'm going to open up the console and now we can see this right here this array with three items inside it so we're getting that data back which is good now this is fine but anyone can access the data and i only want to allow users that are logged in to access the data so you can see right now i'm logged out and i can see this so how do we restrict this data to only people that are logged in well that's where netlify identity comes into play inside our function over here we need to detect whether a user is logged in or not if they are logged in we're going to return this data if they're not logged in we'll return a different response with an error status code so the way we do this is by using this context object that we get access to automatically inside netlify functions and this contains information about the context of the request now on that we have something called the client context so context dot client context and this contains information about the context of the clients making the request in our case the browser so if the browser that's making the request is coming from a person that is logged in then we're going to get access to a user property right here so this property is going to be present only when there is a valid user token coming in on the request i.e when a user is logged in so what i could do is say if and then surround all of this inside the if statement and then paste the return inside this and that means that only if there is a user property present on the client context i.e if a user token is present inside the request then we're going to return this data because if that token is present it means the user is logged in if that's not the case we're going to return something else instead so down here i'm going to say return and inside that return statement we'll do a status code which is going to be 401 meaning unauthenticated let's spell this correctly for a start status code and then we'll also send some data back we'll stringify this so json.stringify um we're just going to send back an object with a message property like so and it will say ah you must be logged in to see this all right then so if now we send a request from the browser whereby a user is logged in this is going to be present and we're going to return this if we send a request where the user is logged out then we're sending this so if i save this now what i'm going to do is come over here and refresh now once i refresh you can see now we're not logged in right we're sending this request from the guides page right here to get this data but we get this error message back so this is working or at least you might think it's working correctly at the minute now watch what happens when i log in so i'm going to say mario at the net ninja dot code uk and then test1234 i'm gonna log in and then once i log in i'm to refresh again and it's going to try to make this request again and we still get an error now two things first of all i want to be able to run this every time the user changes so let me first of all get the user so i'm going to say const and we want the user and that's going to be from use context i'm going to press on this one to auto import it and we want the auth context and we need to import that as well so let me do that at the bottom import auth context from and we need to come out of the current directory then into stores and then we want the auth context file so we're grabbing this user so that we can pass it into the dependency array oops and that means that whenever the user changes ie if they're on this page and they log in then it's going to try to re-fetch the data because it's going to run this again when this is a dependency whenever this changes this value is going to run this so now if i save it we shouldn't have to refresh every time the user either logs out or logs in so if i log out watch this it's gonna hopefully try to make the request again here it does and we get the error back if i try to log in so mario at the net ninja code uk test1234 once i log in it's going to try to make that request again down here we should see that if it works very slow and it does but still we get the 401 response and we get this error message right here so what's going on because we're logged in and we're trying to make this request well by default we don't send the user token inside this fetch request so when the request comes in and we're looking at this the user is not going to be there because it cannot find the token from the user because we're not sending it by default when we use this fetch request we need to send it inside the headers of this request so we add in a second argument to the fetch which is an object and inside here we can say that we want to send some headers so let me do that headers which is an object and oops this needs to be a column inside here we need the authorization and we can spell it the authorization header and we need to pass the token now the way we do that is by saying bearer and then a space and then we concatenate the user token now we have access to the user right here okay let me just for a second comment this out and what i'm going to do is console.log the user down here and then i'm going to say dot token like so so if i save this and come over here you can see we have this token this is the token of the user and on this we have the access token this is the thing we need to send in the fetch request so user.token.access token like so oops that should be underscore so this thing right here we need to send this token with the fetch request right here and when we send it with the fetch request and we run this function that is when the function detects that token and if it's there and if the token is valid that's when we get access to the user property so when we have access to that it returns the correct data if we're logged in so what we need to do is pass this user token right here so let's copy that and we need to pass it into the fetch down here so let's uncomment this and after bearer we pass in the user token like so all right then so this still might not work let me save this and i want to come over here you can see in here it does work we get that data back right but watch what happens if i refresh over here uh we get a big error all right and it says cannot read property token of null and that's because remember to begin with the user right here is null until we've established that connection with netlify to figure out the user so what we really want to do is wait until auth is ready before we try to run this so i can grab authready from this context because remember if we take a look inside our auth context we have the authready state right here which is only true after the init event so after we've established that connection we set off ready to be true so at that point we want to make this fetch request so i'm going to say if and then auth ready like so open up my curly braces and then close them down here is that right yep okay so now we want to scoot this in and scoot this in like so so now only when this is ready and we're going to try to make this fetch request so if i save this now and refresh then now we don't get that big for error let's just do it once more for good measure yep it waits until auth is ready and then it makes the request in our case it figures out that we're logged in and it tries to make that request but watch what happens when i log out you can see now it says cannot read property token of null and if i refresh then it's not going to do that but if i was logged in and then log out it does get that error and that's because when we don't have a user and we're still trying to make this request right here we're trying to access the token on the user but the user is null because we're not logged in so we only want to attach these headers right here if we have a user so the way we do that is just by saying user then logical and and then only when we have a user will it attach this part to the fetch request right here if we don't have a user it won't attach that and so therefore it won't try to access the token it will still make the request and in this case we'll get back the 401 response because we're not logged in but there won't be any errors so let's give this another go so now if i refresh you can see we don't get back any data if i log in as mario at the netninja.cod uk and then test 1234 log in you can see i get this data back now and then if i log out you can see now we get the error message back because we were logged out if i log in again let's just try this once more mario at the net injury.cod.uk and test1234 and try to log in hopefully we'll get the data again yep we do right here and if i refresh when i'm logged in we should get the data as well awesome so now this is good this is all working we're only getting the data back when a user is logged in now one more thing we need to do and that is to pass in here as a dependency auth ready because whenever this changes we also need to re-run the hook because watch this if i was to log out and notice this before and refresh we don't get the error message back right and it should still try to make that request so that we get that error back to say look we're not logged in and the reason it's not making that request is because it's not re-running this use effect function when the author ready changes only when the user changes so we need to pass that in as well auth ready like so so that when this is ready even if we're not logged in it still tries to make that request so now if i'm logged out and try to refresh now we can see we get this error message back and that's better all right then so now we've got this function up and running so that it only sends data back if we're logged in in the next video we'll try to output that data to the browser and if they're not logged in maybe we'll show an error message instead
Original Description
Hey gang, in this tutorial we'll see how netlify functions and netlify identity can work together, so that we can restrict access to data to users not authenticated.
🐱👤 View this course in full without ads on Net Ninja Pro:
https://netninja.dev/p/next-js-with-netlify-identity
🐱💻 Course Files:
+ https://github.com/iamshaunjp/next-netlify-identity
🐱👤 JOIN THE YOUTUBE NET NINJA 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/
+ Netlify Identity docs - https://docs.netlify.com/visitor-access/identity/
+ Netlify Functions docs - https://docs.netlify.com/functions/overview/
🐱💻 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Net Ninja
Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Net Ninja
Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Net Ninja
GraphQL Tutorial #1 - Introduction to GraphQL
Net Ninja
GraphQL Tutorial #2 - A Birdseye View of GraphQL
Net Ninja
GraphQL Tutorial #3 - Project (stack) Overview
Net Ninja
GraphQL Tutorial #4 - Making Queries (front-end preview)
Net Ninja
GraphQL Tutorial #5 - Express App Setup
Net Ninja
GraphQL Tutorial #6 - Setting up GraphQL
Net Ninja
GraphQL Tutorial #7 - GraphQL Schema
Net Ninja
GraphQL Tutorial #8 - Root Query
Net Ninja
GraphQL Tutorial #9 - The Resolve Function
Net Ninja
GraphQL Tutorial #10 - Testing Queries in Graphiql
Net Ninja
GraphQL Tutorial #11 - GraphQL ID Type
Net Ninja
GraphQL Tutorial #12 - Author Type
Net Ninja
GraphQL Tutorial #13 - Type Relations
Net Ninja
GraphQL Tutorial #14 - GraphQL Lists
Net Ninja
GraphQL Tutorial #15 - More on Root Queries
Net Ninja
GraphQL Tutorial #16 - Connecting to mLab
Net Ninja
GraphQL Tutorial #17 - Mongoose Models
Net Ninja
GraphQL Tutorial #18 - Mutations
Net Ninja
GraphQL Tutorial #19 - More on Mutations
Net Ninja
GraphQL Tutorial #20 - Updating the Resolve Functions
Net Ninja
GraphQL Tutorial #21 - GraphQL NonNull
Net Ninja
GraphQL Tutorial #22 - Adding a Front-end
Net Ninja
GraphQL Tutorial #23 - Create React App
Net Ninja
GraphQL Tutorial #24 - Book List Component
Net Ninja
GraphQL Tutorial #25 - Apollo Client Setup
Net Ninja
GraphQL Tutorial #26 - Making Queries from React
Net Ninja
GraphQL Tutorial #27 - Rendering Data in a Component
Net Ninja
GraphQL Tutorial #28 - Add Book Component
Net Ninja
GraphQL Tutorial #29 - External Query File
Net Ninja
GraphQL Tutorial #30 - Updating Component State
Net Ninja
GraphQL Tutorial #31 - Composing Queries
Net Ninja
GraphQL Tutorial #32 - query variables
Net Ninja
GraphQL Tutorial #33 - Re-fetching Queries
Net Ninja
GraphQL Tutorial #34 - Book Details Component
Net Ninja
GraphQL Tutorial #36 - Styling the App
Net Ninja
GraphQL Tutorial #35 - Making a Single Query
Net Ninja
Build Apps with Vue & Firebase - Udemy Course
Net Ninja
Updated Vue & Firebase Course (Udemy)
Net Ninja
Vue & Firebase Real-time Chat (Preview) #1 - Intro
Net Ninja
Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Net Ninja
Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Net Ninja
Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Net Ninja
Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Net Ninja
Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Net Ninja
Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Net Ninja
Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Net Ninja
Object Oriented JavaScript Tutorial #1 - Introduction
Net Ninja
Object Oriented JavaScript Tutorial #2 - Object Literals
Net Ninja
Object Oriented JavaScript Tutorial #3 - Updating Properties
Net Ninja
Object Oriented JavaScript Tutorial #4 - Classes
Net Ninja
Object Oriented JavaScript Tutorial #5 - Class Constructors
Net Ninja
Object Oriented JavaScript Tutorial #6 - Class Methods
Net Ninja
Object Oriented JavaScript Tutorial #7 - Method Chaining
Net Ninja
Object Oriented JavaScript Tutorial #8 - Class Inheritance
Net Ninja
Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Net Ninja
Object Oriented JavaScript Tutorial #10 - Prototype
Net Ninja
Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Net Ninja
More on: Auth & Authorisation
View skill →Related Reads
📰
📰
📰
📰
Inside the Wayfair Frontend SDE-2 Interview: A Complete Breakdown
Medium · Programming
I Spent Two Years Maintaining a React SPA. HTMX Rebuilt It in a Week
Medium · Programming
The 5 Levels of Front End Engineering (And Where Most Developers Get Stuck)
Medium · Programming
Browser-Based PDF Editing with Vue 3 and pdf-lib
Dev.to · sunshey
🎓
Tutor Explanation
DeepCamp AI