Building a user authentication app with React and Django Rest Framework

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
The nature of the communication between a web browser and a server over HTTP is stateless this means that each request is anonymous with no relation to the other requests and the server does not keep track of the user interacting with it on the frontend if you've used Django before, you're probably familiar with all the nice features it provides for example you can set up a user authentication app within minutes making those client/server requests identifiable and traceable the server having some information stored in the database can work out who this request was sent by you can write your Django backend as a REST API using the Django Rest Framework and instead of using dynamic HTML templates on the frontend you can use a Javascript library like React and write a single page application in this way you benefit from 2 of the most popular web development tools nowadays the Django API will run at localhost 8000 and the React frontend at localhost 3000 React will send requests to Django using Axios and we will use session authentication sessions are stateful and they work like this: a user sends login credentials the server validates them and generates a session the session is stored on the backend and the session ID is sent to the browser the session ID is stored in the browser as a cookie and is sent every time the user sends a request to the server if you're more interested in something like JSON Web Tokens for authentication you can watch a video I made specifically on that here on this channel let's first build the REST API we will start by installing django-cors-headers and djangorestframework and add them under INSTALLED_APPS also add corsheaders middleware to the top of the MIDDLEWARE set CORS_ALLOWED_ORIGINS to allow interaction with React and CORS_ALLOW_CREDENTIALS to True create the user_api app and add it to INSTALLED_APPS I've used a custom user model for the user API if you want to learn more about this model you can watch a video I made on it specifically here on this channel the next thing to do is to determine the endpoints of the API there will be 4 a user registration path, login, logout and a user path that logged in users can access we will fill those out once we've written the views we move on to writing the serializers we will have 3, for registration, login and user view the registration 1 will be a model serializer it will have a create method that will use the user model to create a new user the login serializer will be responsible for authenticating the username and password of the user the user serializer will be based on the model and returns the user moving on to the views, we do a bulk import here we will have 4 classes, 1 for every URL they will inherit from APIView from the rest framework views the user registration class will be accessed by anyone it will only have a POST method we will clean up the data it receives before feeding it to the serializer this is a custom validation method that I've created in validations.py you can validate whatever you want once the data passes all checks we can create a new user using the serializer method and return the response accordingly the login view will also be accessed by anyone it will make use of session authentication we write the POST method again some data validation if everything looks fine we can authenticate the user, and log them in the logout view will have a POST method and it will run the logout command the user view will assume the user request is authenticated it will have a GET method that returns the user we can go back and update the URLs file to set the views for each path also remember to set the AUTH_USER_MODEL in settings.py to the custom user model and set the REST_FRAMEWORK variable now we can run the API locally to try out the endpoints the registration endpoint we can paste in some user data here and click POST the user got registered now let's log in using the email and password the user is now logged in we can go to the user view and see the user data sent back we then log out by clicking on the POST button and now we can no longer access the user view you can also see the session ID being set from the browser console so before we log in, there is no session ID when we log in, the session ID now appears it is also there for the user view when we log out it disappears now that the Django API appears to be running as expected on it own we want to start using it from the React frontend so we'll move on to writing the React frontend using the create-react-app tool we can create a React project called frontend we will install some modules like Axios, react-bootstrap and Bootstrap the bulk of our code will be in App.js we will do all the imports we're going use as well as some Bootstrap imports we set some default Axios variables like ensuring the CSRF token gets sent with the requests we make to Django we create a client instance with a base URL so that we only have to type in the Django API address once we move on to writing the app functional component we can set up some variables using useState and we will be able to update them throughout the code using their corresponding methods the current user variable helps us check if a current user is there the registration toggle variable helps us toggle between the login and registration forms and some user input variables next we want to create the actual user forms I will copy over some of the example forms on the react-bootstrap website and do some modification those include a navbar and some forms we now update the return section of the app component if a current user exists, the app component will return a navbar with a logout button and a div with a "you're logged in" message if there is no active current user we will return a navbar with a register button that allows us to toggle between the register and login forms displayed on the page this is done using the "update_form_btn" handler which we will create shortly we use the registration toggle to determine what JSX will be returned either a registration form or a log in form depending on the toggle click we can create the toggle function in the app component above the return section when the button is clicked we will update the button inner HTML and the registration toggle state we can now create some handlers that will handle user registration, login and logout submissions the first being submit registration it takes the event as argument we use React’s "preventdefault" to prevent browser reload/refresh this will submit the registration form using the stateful variables it will also send in a login request so that the user is logged in after registering and we update the current user variable to true the login handler is similar in that it sends login details to the Django API the logout handler sends a logout request to the API next we use the useEffect hook to determine if the user is logged in by sending a GET request to the user API endpoint and update current user to true or false depending on the response we don't want to run it too often so we pass the empty array as argument now to try things out, we start the Django server we start the React app and we go to the 127 local address in the browser it is important that we use this IP address instead of the localhost alias here we can toggle between the registration and the log in forms we open the browser console to view the cookie let's register a new user when we click submit it also logs us in and in storage we see a new session ID if we log out, the session ID is removed we can log back in with the same user and watch the session ID again this authentication app is minimal but it will hopefully help you understand how to use React with Django Rest Framework the Axios library that we used does make the code more concise and easier to read the code for this video will be linked in the description and I will see you in the next video.
Info
Channel: Django road
Views: 51,964
Rating: undefined out of 5
Keywords: django, django rest framework, DRF, React, ReactJS, API, frontend, backend, web development, user authentication, session authentication
Id: diB38AvVkHw
Channel Id: undefined
Length: 15min 25sec (925 seconds)
Published: Tue Mar 07 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.