![]() The important thing is to add the default headers to the axios api instance once we find a valid token in the cookies // contexts/auth.js Create a new file called api.js // api.js This will define how we connect to our backend. Now, let’s start by the axios api instance. ![]() We need a backend to return an authentication token when a correct login is done (this is out of the scope of this tutorial, send me an email if you’d like to see how that is done.įirst install the dependencies that we will need yarn add js-cookie axios swr Skeleton.We need to show an example of how a data request is done.We need to display something while the data loads (in our case, instead of a spinner, we will implement a skeleton loader).We need to alter the default headers of our fetch library (in our case, axios) to include the auth token in all requests.We need to create a Higher Order Component (HOC) that makes use of that context and protects routes accordingly.We need to make that context available to all of our app, by modifying the custom _app.js page and wrapping the root Component Tag with our auth context provider.We need to create a React Context that will hold our user.When the request is done, the client rerenders with the data, or redirects the user to /login, accordingly.The client side fetch will be authenticated or not and your api will return the data or a 401 error accordingly.While this happens the user has already seen a first paint of your site.On the client side, fetch requests ping your api for the private data.When a user requests the page, NextJS serves the structure of the page.At compile time you statically generate the structure of the protected page.Later on the client side, you fetch the data that you need, and show a loading skeleton while it does. In this way, if you don’t check for authentication on the server, you can prevent adding getServerSideProps to your pages.Īnd if your pages don’t provide a getServerSideProps, then your site will be blazingly fast, because it will be statically rendered. Instead simply protect the api routes that return the private data that you need. Now, once you understand these three ways of rendering, NextJS also introduces a different mindset when thinking authentication.ĭo not check for authentication of your pages on the server. Client side render your pages, when you navigate from one page to another (after the first render when your user landed on your site).Server side render your pages on each request, in case you add getServerSideProps to a page.Statically render the structure of the page when you compile your project in all the pages that don’t have getServerSideProps.Before understanding the auth flow, we need to make clear the how NextJS works Understanding the 3 types of renderingįirst of all you need to understand how next js renders things.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |