<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mahieyin Rahmun on Medium]]></title>
        <description><![CDATA[Stories by Mahieyin Rahmun on Medium]]></description>
        <link>https://medium.com/@mahieyin-rahmun?source=rss-edbf06d22cc4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*i9rK23xKefeZ00OatMZR4Q.jpeg</url>
            <title>Stories by Mahieyin Rahmun on Medium</title>
            <link>https://medium.com/@mahieyin-rahmun?source=rss-edbf06d22cc4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 13:15:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mahieyin-rahmun/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to setup a GraphQL server in Next.js with API endpoints]]></title>
            <link>https://mahieyin-rahmun.medium.com/how-to-setup-a-graphql-server-in-next-js-with-api-endpoints-27aa4001c20b?source=rss-edbf06d22cc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/27aa4001c20b</guid>
            <category><![CDATA[typegraphql]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[typeorm]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Mahieyin Rahmun]]></dc:creator>
            <pubDate>Wed, 23 Jun 2021 06:22:59 GMT</pubDate>
            <atom:updated>2021-06-24T17:47:13.979Z</atom:updated>
            <content:encoded><![CDATA[<p>using TypeScript, type-graphql and apollo-server-micro</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hef_UyB9p00HxJuJ" /><figcaption>Photo by <a href="https://unsplash.com/@jstrippa?utm_source=medium&amp;utm_medium=referral">James Harrison</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I have been learning GraphQL for a while now, and I love Next.js for the benefits it comes with. So, one morning, I decided to try and combine the two and see if I can make it work. The journey was not as smooth as I expected it to be, so I decided to document my approach. Specifically, I had two issues:</p><ul><li>You need to get your configurations correct to make decorators play along nicely.</li><li>You need to have a specific way of creating database connections to not clash with Next.js’ Hot Module Reloading (HMR).</li></ul><p>The aim of this article is to give you a boilerplate that will work for Next.js and GraphQL combined without any issues.</p><p><em>Disclaimer: This article assumes some knowledge about TypeScript, Next.js and API routes, GraphQL, PostgreSQL database and TypeORM.</em></p><h3>Creating a new Next.js App</h3><p>To start things off, we create a new Next.js app. I will be using yarn , but the same should be achievable with npm as well.</p><pre>mkdir nextjs-graphql<br>cd nextjs-graphql<br>yarn create next-app . --typescript</pre><p>The above series of commands will create a basic Next.js template app with TypeScript in the nextjs-graphql directory.</p><p>I will make the folder structure a bit more manageable by deleting a few files, but this is optional. This is how my folder structure looks like after deleting some of the files:</p><pre>tree . -L 2 -I node_modules</pre><pre>.<br>├── next.config.js<br>├── next-env.d.ts<br>├── package.json<br>├── pages<br>│   └── _app.tsx<br>├── public<br>│   ├── favicon.ico<br>│   └── vercel.svg<br>├── README.md<br>├── tsconfig.json<br>└── yarn.lock</pre><h3>Installing dependencies</h3><p>Let’s start off by installing the dependencies that we need.</p><pre>yarn add graphql apollo-server-micro reflect-metadata type-graphql class-validator</pre><ul><li>graphql is self-explanatory.</li><li>apollo-server-micro is the package that will allow us to instantiate an ApolloServer instance.</li><li>type-graphql <a href="https://typegraphql.com/">is a framework for building GraphQL API</a> using TypeScript. It has a dependency on reflect-metadata and class-validator.</li></ul><h3>Setting up a resolver and API endpoint</h3><p>If you are not familiar with type-graphql , I suggest reading up on their <a href="https://typegraphql.com/docs/installation.html">amazing documentation</a>. If you want to learn more about type-graphql , I recommend <a href="https://github.com/benawad/type-graphql-series">Ben Awad’s tutorial series on </a><a href="https://github.com/benawad/type-graphql-series">type-graphql</a> .</p><p>We will create a hello world resolver to test things out with our GraphQL API. type-graphql includes some decorators to annotate classes which will let GraphQL know about the schema and will enable type safety in the queries. Create a file HelloWorldResolver.ts under /lib/serverless/graphql/resolvers .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6a899decd90ba921b29522572378736/href">https://medium.com/media/e6a899decd90ba921b29522572378736/href</a></iframe><p>As you can see, we are importing Resolver and Query decorators to annotate our resolver class. And for now, we are simply returning a string from the resolver.</p><p>At this point, your IDE should be complaining about decorators and how you need to enable a certain feature to resolve the warnings. We will deal with that later, because that is only a fragment of the issues we need to deal with. For now, we want to setup our API handler for GraphQL. Create a file index.ts under /pages/api/graphql .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca20f3bce8a73bf839a8f49d6aad9cd5/href">https://medium.com/media/ca20f3bce8a73bf839a8f49d6aad9cd5/href</a></iframe><p>We are doing a few things here:</p><ul><li>Import reflect-metadata package at the very top. If you have used TypeORM before, you would be familiar with this.</li><li>We are importing ApolloServer from apollo-server-micro</li><li>We are importing buildSchema from type-graphql , which will allow us to build schema definitions directly from our annotated resolvers. Hence, we do not need gql template strings for type definitions.</li><li>We are disabling bodyParser of Next.js API endpoint, so that GraphQL is the one handling responses from the route.</li><li>Finally, after instantiating our ApolloServer instance, we are exporting, by default, the GraphQL handler for this particular API endpoint. So, when you want to perform queries, you would need to send them to <a href="http://localhost:3000/api/graphql.">http://localhost:3000/api/graphql.</a></li></ul><p>At this point, you should see another error, saying that you cannot use top-level await. Now, we will deal with resolving those issues.</p><h3>Resolving the configuration issues</h3><p>Even if you try to launch the application using yarn dev right now, you won’t be able to reach the GraphQL endpoint. Because, we need to take care of some configuration before our TypeScript files can be properly transpiled and bundled by webpack. Next.js by default doesn’t have support for decorators enabled. There are four steps to this:</p><ul><li>Modifying tsconfig.json</li></ul><p>We need to explicitly say that we want decorator support in our app. So, add the following lines in your tsconfig.json , under compilerOptions :</p><pre>&quot;target&quot;: &quot;es2018&quot;,<br>&quot;lib&quot;: [&quot;dom&quot;, &quot;dom.iterable&quot;, &quot;esnext&quot;, &quot;esnext.asynciterable&quot;],<br>&quot;emitDecoratorMetadata&quot;: true,<br>&quot;experimentalDecorators&quot;: true,</pre><ul><li>Installing a few dependencies</li></ul><pre>yarn add -D <a href="http://twitter.com/babel/core">@babel/core</a> <a href="http://twitter.com/babel/plugin-proposal-decorator">@babel/plugin-proposal-decorator</a>s <a href="http://twitter.com/babel/plugin-proposal-class-pro">@babel/plugin-proposal-class-pro</a>perties babel-plugin-transform-typescript-metadata</pre><ul><li>Creating a .babelrc file</li></ul><p>Create a .babelrc file at the root directory of your app and enable the support for decorators. <strong>Note that the ordering of the plugins matter in this case. </strong>This has been mentioned <a href="https://github.com/vercel/next.js/issues/4707#issuecomment-659231837">in this particular GitHub issue on Next.js repository.</a></p><pre>{<br>  &quot;presets&quot;: [&quot;next/babel&quot;],<br>  &quot;plugins&quot;: [<br>    &quot;babel-plugin-transform-typescript-metadata&quot;,<br>    [&quot;<a href="http://twitter.com/babel/plugin-proposal-decorator">@babel/plugin-proposal-decorator</a>s&quot;, { &quot;legacy&quot;: true }],<br>    [&quot;<a href="http://twitter.com/babel/plugin-proposal-class-pro">@babel/plugin-proposal-class-pro</a>perties&quot;, { &quot;loose&quot; : true }]<br>  ]<br>}</pre><ul><li>Modifying webpack configuration in next.config.js</li></ul><p>You also need to enable top-level await in your webpack config, which should be done in your next.config.js</p><pre>module.exports = {<br>  reactStrictMode: true,<br>  webpack: function (config, options) {<br>    config.experiments = { topLevelAwait: true }<br>    return config;<br>  }<br>}</pre><p>After these steps, you should be able to reach the GraphQL API endpoint at <a href="http://localhost:3000/api/graphql,">http://localhost:3000/api/graphql</a> after running yarn dev, and you should be able to see the GraphQL playground and run queries it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EmHBhWvBWcGSbURxWHs--Q.png" /><figcaption>Functioning GraphQL API endpoint</figcaption></figure><h3>Practical Example</h3><p>Let’s extend our endpoint further by using a real world example of user registration and see if it can withstand a real world use-case.</p><h3>Setting up a database</h3><p>Let’s setup a postgres database locally. I will be using the commands listed <a href="https://medium.com/coding-blocks/creating-user-database-and-adding-access-on-postgresql-8bfcd2f4a91e">in this medium.com article</a>.</p><pre>sudo -u postgres psql<br>create database nextjs_graphql;<br>create user nextjs with encrypted password &#39;nextjs&#39;;<br>grant all privileges on database nextjs_graphql to nextjs;</pre><p>With the database created, you can now create a database connection. Let’s create a file db.ts in /lib/serverless/utils/ folder. I will be referring to <a href="https://dev.to/unframework/getting-typeorm-to-work-with-next-js-and-typescript-1len">this article</a> which explains how to properly create a database connection that doesn’t clash with Next.js’ Hot Module Reloading.</p><p>Let’s not forget to install the necessary packages:</p><pre>yarn add typeorm pg</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5af1ba564ef76fc9616aeb6ddf733da5/href">https://medium.com/media/5af1ba564ef76fc9616aeb6ddf733da5/href</a></iframe><p>Note that we will create the User.ts file shortly.</p><p>And now, you can modify the index.ts file under /pages/api/graphql/ . You can pass the database connection object to your resolvers through the context . However, we will not be using it in this article, but it’s left here to serve as an example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef0c41adcb892b3837855636111b8f45/href">https://medium.com/media/ef0c41adcb892b3837855636111b8f45/href</a></iframe><p>Note that we will be creating the UserResolver.ts file shortly.</p><p>Let’s create a file User.ts under /lib/serverless/entities/ . We will be using a lot of decorators in this one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38eeb39698d47d741b3db70167a8229f/href">https://medium.com/media/38eeb39698d47d741b3db70167a8229f/href</a></iframe><p>Let’s see what’s going on here:</p><ul><li>First, we extend from the BaseEntity class of typeorm . This allows us to readily call methods like user.create() or user.find() without requiring to obtain a connection object or a repository.</li><li>We use the decorators from typeorm to convert the class into a database entity. We use the @Entity and @Column decorators for this.</li><li>Next, we need to be able to specify that this class will also be used as a GraphQL object type, which is why we are also using the decorators from type-graphql , namely @ObjectType and @Field decorators.</li></ul><p>Finally, we need to write the resolver for the User entity, which we will do in the UserResolver.ts file under /lib/serverless/graphql/resolvers/ .</p><p>We have a mutation registerUser and a query getUser . They take their corresponding input parameters to save a user to the database and return a user from the database, if any, respectively.</p><p>Just to save some time, I will not be hashing the password before saving it to the database, but it is recommended that you hash any sensitive information before storing it in a database.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/403777b7c9574028bfe1100a2f63da28/href">https://medium.com/media/403777b7c9574028bfe1100a2f63da28/href</a></iframe><p>And with that, we are done setting up. This is the final folder structure of the project after all the modifications above:</p><pre>.<br>├── lib<br>│   └── serverless<br>│       ├── entities<br>│       │   └── User.ts<br>│       ├── graphql<br>│       │   └── resolvers<br>│       │       ├── HelloWorldResolver.ts<br>│       │       └── UserResolver.ts<br>│       └── utils<br>│           └── db.ts<br>├── next.config.js<br>├── next-env.d.ts<br>├── package.json<br>├── pages<br>│   ├── api<br>│   │   └── graphql<br>│   │       └── index.ts<br>│   └── _app.tsx<br>├── public<br>│   ├── favicon.ico<br>│   └── vercel.svg<br>├── README.md<br>├── tsconfig.json<br>└── yarn.lock</pre><p>You can hop onto your GraphQL playground at http://localhost:3000/api/graphqland verify that the queries and mutations are working. I have also tested this in production environments using yarn build &amp;&amp; yarn start to verify that nothing breaks in production.</p><p>The entire code for the article can be found <a href="https://github.com/mahieyin-rahmun/NextJSWithGraphQL">in this repository</a>. Let me know your thoughts and feedback.</p><p>Go Beyond!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27aa4001c20b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[(Part 2) How to configure social authentication in a Next.js]]></title>
            <link>https://mahieyin-rahmun.medium.com/part-2-how-to-configure-social-authentication-in-a-next-js-183984761e97?source=rss-edbf06d22cc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/183984761e97</guid>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[nextauth]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[Mahieyin Rahmun]]></dc:creator>
            <pubDate>Fri, 30 Apr 2021 08:04:26 GMT</pubDate>
            <atom:updated>2021-04-30T08:56:39.122Z</atom:updated>
            <content:encoded><![CDATA[<h3>(Part 2) How to configure social authentication in a Next.js + Next-Auth + Django Rest Framework application</h3><h4>with automated refreshing of access tokens and discussing the pitfalls of useSession() hook (as of Apr 30, 2021)</h4><p><em>This is the second part of a two-part series where I show you a way to connect your Django Rest Framework backend with a Next.js + Next-Auth app. If you are looking for the first part in the series where I lay out the basic concepts and write the first part of the code that only deals with obtaining access tokens from the DRF backend to use in the Next.js + Next-Auth client, head over </em><a href="https://mahieyin-rahmun.medium.com/how-to-configure-social-authentication-in-a-next-js-next-auth-django-rest-framework-application-cb4c82be137"><em>here</em></a><em>.</em></p><blockquote>Disclaimer: The pitfalls of the useSession() hook of the next-auth package mentioned in this article is valid at the time of writing, but may not be the case depending on when you are reading this. The solution to the pitfall is currently being <a href="https://github.com/nextauthjs/next-auth/issues/596#issuecomment-736678198">actively worked on</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*vwispdXsE9l66MP88fcxtQ.png" /></figure><p>In my last <a href="https://mahieyin-rahmun.medium.com/how-to-configure-social-authentication-in-a-next-js-next-auth-django-rest-framework-application-cb4c82be137">article</a>, I talked about the basic template of configuring a Next.js + NextAuth app with Django Rest Framework. It works, but it has some flaws:</p><ul><li>No way to use the refresh token</li><li>useSession() happens to have its own set of pitfalls (more on that later)</li></ul><p>Even though dj-rest-auth package gives us endpoints to obtain rotating access and refresh tokens, we are not making use of those endpoints. Let’s fix that.</p><h3><strong>Refreshing access token</strong></h3><p>In order to refresh the access token, we need to understand how the Next-Auth flow works. You can find the details in the <a href="https://next-auth.js.org/configuration/callbacks">Next-Auth documentation on callbacks</a>, but basically:</p><ul><li>User logs in. The code in [...nextauth].ts is going to run.</li><li>The first callback to get immediately called after sign in is the signIn() callback.</li><li>After that, the jwt() and session() callbacks are called in succession.</li><li>Each time you use useSession() or getSession() , the jwt() and session() callbacks are run again.</li></ul><p>As such, the refreshing mechanism needs to be done in the jwt() callback, and any modifications to be done to the session object is done in the session() callback. So, let’s do some modifications to the pages/api/auth/[...nextauth].ts file. Before that, create a new file client/constants/Utils.ts :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5104b8dd3a066ae5abc156287630a775/href">https://medium.com/media/5104b8dd3a066ae5abc156287630a775/href</a></iframe><p>This file contains two functions: one to check for JWT token expiration, and the other for creating API endpoints. We depend on the jsonwebtoken package, which you can install by running yarn add jsonwebtoken and yarn add -D @types/jsonwebtoken if you need the type definitions. We will be using these two functions in the client/pages/api/auth/[...nextauth].ts file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a2bb0f287ab3f406aafdefada517e1e/href">https://medium.com/media/0a2bb0f287ab3f406aafdefada517e1e/href</a></iframe><p>If you are here from <a href="https://mahieyin-rahmun.medium.com/how-to-configure-social-authentication-in-a-next-js-next-auth-django-rest-framework-application-cb4c82be137">Part 1 of my article</a>, you would notice that the signIn() function is missing, and the associated logic is now inside jwt() callback. This was done after consultation with one of the maintainers of Next-Auth. You can read the conversation <a href="https://github.com/nextauthjs/next-auth/discussions/1350#discussioncomment-643767">here</a>, but basically, monkey-patching the user object the way I was doing it before is not actually needed. The rest of the code is self-explanatory: we check the expiration time of the access token, if it is nearly expired (refer to the Utils.ts file, we are offsetting current time by 60 seconds), then try to refresh it by communicating with the DRF backend. Also notice that we have refactored the backend base API endpoint into an environment variable.</p><p>Right now, with the current modifications in the [...nextauth].ts file, you have the ability to refresh the access tokens from the DRF backend, as long as the refresh token itself is valid.</p><p>All looks good, right? Well… not quite.</p><h3>Pitfalls of the useSession() hook</h3><p>Remember that in our client/pages/index.tsx file, we have the following code with the useSession() hook:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d7efff0966af6655305bde140266282/href">https://medium.com/media/2d7efff0966af6655305bde140266282/href</a></iframe><p>It turns out that currently <a href="https://github.com/nextauthjs/next-auth/issues/596">there is an issue with the </a><a href="https://github.com/nextauthjs/next-auth/issues/596">useSession() hook</a> as well as the getSession() function, which prevents them from automatically getting the updated sessionobject after the access token is refreshed. <strong>In other words, unless you do a hard page refresh, you won’t get the updated access token in your client and your subsequent API requests to the DRF backend that require a valid token will fail.</strong></p><p>If you are looking for an example, I actually have one set up in the associated <a href="https://github.com/mahieyin-rahmun/NextJsWithDRFExample">Github repository</a>. For the brevity of this article, I am not going to write out everything, but the gist of it is:</p><ul><li>There is a posts app in the <a href="https://github.com/mahieyin-rahmun/NextJsWithDRFExample/tree/main/backend/posts">DRF backend</a>. The only view in the views.py file pings <a href="https://jsonplaceholder.typicode.com/posts">JSONPlaceholder</a> and returns the posts it can find. This route requires authentication, e.g. the access token.</li><li>At the <a href="https://github.com/mahieyin-rahmun/NextJsWithDRFExample/blob/main/client/pages/posts.tsx">frontend</a>, I am polling the above API endpoint at regular intervals of 10 seconds. Once the access token expires, even though it is being refreshed in the jwt() callback, the client still has the old access token. Therefore, the subsequent calls to the API will return 401 Unauthorized .</li></ul><p>So, then, what’s the solution?</p><h3>Custom useAuth() hook with useSwr()</h3><p>To solve/work around the above problem, an approach that I came up with following this <a href="https://github.com/nextauthjs/next-auth/issues/596#issuecomment-760251882">comment</a> is to use the useSwr() hook in the <a href="https://swr.vercel.app/">swr</a> package. Install the package first by running yarn add swr . I created a custom hook that will ping the <a href="https://next-auth.js.org/getting-started/rest-api#get-apiauthsession">session REST API provided by Next-Auth</a> at regular intervals to keep the session object updated.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e0f1a303dc9e3b02680151c4ed39e4c/href">https://medium.com/media/7e0f1a303dc9e3b02680151c4ed39e4c/href</a></iframe><blockquote>Side note about the approach above: I was actually reluctant to use this approach and instead wanted to get it done using built-in React hooks, namely<em>useState()</em> and <em>useEffect()</em> . However, I failed to do so, as you will see <a href="https://github.com/mahieyin-rahmun/NextJsWithDRFExample/blob/main/client/constants/Hooks.tsx">in this file in the Git repository</a>. For those of you who are interested to know, <strong>the issue with using built-in hooks was that the page would arbitrarily refresh itself after the </strong><strong><em>setInterval()</em> callback fired,</strong> which results in absolutely crap user experience. Hence, I had to settle for a solution with the <em>useSwr()</em> hook. If any of you are able to solve the issue using built-in hooks, feel free to make a pull request in the Git repository.</blockquote><p>So, now you can replace all calls to useSession() with useAuth() .</p><pre>- const [session, loading] = useSession();<br>+ const { session, loading } = useAuth(); // default 20 seconds refresh interval for session</pre><pre>// OR, if you want to have custom refresh interval<br>+ const { session, loading } = useAuth(3 * 60); // 3 minutes refresh interval for session</pre><h3>Higher Order Component to get rid of code repetition (optional)</h3><p>The last piece of the puzzle came in the form of a HOC, since I did not want to write the following lines in every single page of the app:</p><pre>if (typeof window !== &#39;undefined&#39; &amp;&amp; loading) {<br>  return null;<br>}</pre><pre>if (!loading &amp;&amp; !session) {<br>  return &lt;AccessDenied /&gt;<br>}</pre><pre>return &lt;MyComponent /&gt;</pre><p>As such, I created a withAuth HOC.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bedd20b4fb09dc1c2d7d6d3d91d240bc/href">https://medium.com/media/bedd20b4fb09dc1c2d7d6d3d91d240bc/href</a></iframe><p>Now, you can export your components by wrapping it with this HOC, and it will take care of handling the session object and showing an Access Denied component if the user is not logged in.</p><pre>// default session refresh interval of 20 seconds<br>export default withAuth()(Posts);</pre><pre>// session refresh interval of 3 minutes<br>export default withAuth(3 * 60)(Posts);</pre><h3>Conclusion</h3><p>This took way longer than I anticipated, but I learnt a lot in the process. I hope this series of articles was able to help you out in some ways to connect your Django backend with a Next.js + Next-Auth app. In hindsight, the same principles should apply for connecting basically any custom backend with Next-Auth and Next.js.</p><p>Feel free to leave your comments/criticisms/suggestions. The associated Github repository for all the code can be found <a href="https://github.com/mahieyin-rahmun/NextJsWithDRFExample">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=183984761e97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to configure social authentication in a Next.js + Next-Auth + Django Rest Framework application]]></title>
            <link>https://mahieyin-rahmun.medium.com/how-to-configure-social-authentication-in-a-next-js-next-auth-django-rest-framework-application-cb4c82be137?source=rss-edbf06d22cc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb4c82be137</guid>
            <category><![CDATA[google-oauth]]></category>
            <category><![CDATA[nextauth]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[Mahieyin Rahmun]]></dc:creator>
            <pubDate>Wed, 17 Feb 2021 04:52:18 GMT</pubDate>
            <atom:updated>2021-04-30T08:07:59.588Z</atom:updated>
            <content:encoded><![CDATA[<h3>(Part 1) How to configure social authentication in a Next.js + Next-Auth + Django Rest Framework application</h3><h4>with a custom Django user model</h4><blockquote>This is the first part of a two-part series where I show you a way to connect your Django Rest Framework backend with a Next.js + Next-Auth app. If you are looking for the second part in the series where I discuss refresh tokens and common pitfalls of useSession() hook (as of Apr 30, 2021), head over <a href="https://mahieyin-rahmun.medium.com/part-2-how-to-configure-social-authentication-in-a-next-js-183984761e97">here</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*-I-3vAfxhZ6QUe17E2clSw.png" /></figure><p>Authentication has always been a gigantic pain in the you-know-where, at least for me. I come from a Node.js, <a href="https://expressjs.com/">Express.js</a> background, where I used <a href="http://www.passportjs.org/">passport.js</a> to handle authentication schemes. I started learning <a href="https://www.djangoproject.com/">Django</a> and <a href="https://www.django-rest-framework.org/">Django Rest Framework (DRF)</a>. However, Django (and DRF, for that matter) does a lot of heavy lifting behind the scenes, which is why it seems quite perplexing (again, most likely only to me) to do many things. Not to mention that one of my acquaintances actually said it out loud that:</p><blockquote>Django OAuth schemes kinda seem shady at times</blockquote><p>And I kind of have to agree to that, as I tried a bunch of different solutions and none of them worked perfectly the way I wanted them to. That is why I sat down a few hours ago to embark on a mission to find out once and for all whether what I want to do is actually possible:</p><blockquote>Use a <a href="https://nextjs.org/">Next.js</a> frontend with <a href="https://next-auth.js.org/">Next-Auth</a> for the authentication, but at the same time have a separate backend (in my case, DRF) so that I can essentially have the best of both worlds in my web application.</blockquote><h3><strong>Okay, but how?</strong></h3><p>For this tutorial, we will set up a basic DRF application to serve as our backend and later have a Next.js application communicate with it. Since Next-Auth does a really nice job of hooking up Social Authentication with your Next.js app, we want to be able to keep that flow, and make the DRF backend takeover when we want it to. Essentially, Next-Auth will act sort of like a middleman between the Next.js app and the DRF backend. We will use Google Sign-in as part of the example, but other providers should follow a similar approach. So, let’s get started!</p><h3><strong>The Flow</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*fPZwj_ixt2LzgxZcwy2ULg.png" /><figcaption><strong>The entire application flow</strong></figcaption></figure><h3>Project structure</h3><p>I will be on a Ubuntu 20.04 machine, however the OS should not be of any importance. Let’s setup a basic folder structure. The names of the folders are self-explanatory.</p><pre>$ cd Documents/Code # or wherever you prefer keeping your code files<br>$ mkdir -p next-js-with-drf/client next-js-with-drf/backend<br>$ tree next-js-with-drf  # a handy tool to inspect folder structures</pre><pre>next-js-with-drf <br>├── backend <br>└── client</pre><h3>Backend</h3><p>For the backend, we need to install quite a few packages. I am assuming you know already how to spin up a virtual environment and setup a basic Django application. I prefer using conda, but you can use virtualenv as well.</p><pre>$ conda create -n next-js-with-drf python=3.7<br>... (truncated output)<br>Preparing transaction: done<br>Verifying transaction: done<br>Executing transaction: done<br>#<br># To activate this environment, use<br>#<br>#     $ conda activate next-js-with-drf</pre><pre>$ conda activate next-js-with-drf</pre><p>Then, we need to install the required packages:</p><pre>$ pip install django djangorestframework django-cors-headers dj-rest-auth django-allauth djangorestframework-simplejwt</pre><ul><li>Django and DRF are obvious</li><li>Django CORS Headers: Needed to allow cross-domain communication (e.g. DRF backend running on http://127.0.0.l:8000 can’t be readily accessed by Next.js frontend running on http://127.0.0.l:3000)</li><li><a href="https://dj-rest-auth.readthedocs.io/en/latest/">DJ Rest Auth</a>: API endpoints for RESTful authentication</li><li><a href="https://django-allauth.readthedocs.io/en/latest/overview.html">Django AllAuth</a>: For Authentication using Social Accounts (in this example, Google)</li><li><a href="https://django-rest-framework-simplejwt.readthedocs.io/en/latest/">DjangoRestFramework SimpleJWT</a>: Needed to issue access_token and refresh_token when a user logs in/signs up.</li></ul><p>After the packages finish installing, let’s setup our Django project.</p><pre>$ cd next-js-with-drf/backend<br>$ django-admin startproject nextjsdrfbackend .<br>$ django-admin startapp nextjsdrfauth</pre><pre>$ cd nextjsdrfbackend</pre><pre>$ touch secrets.py secrets.example.py<br>$ tree ../<br>../<br>├── manage.py<br>├── nextjsdrfauth<br>│   ├── admin.py<br>│   ├── apps.py<br>│   ├── __init__.py<br>│   ├── migrations<br>│   │   └── __init__.py<br>│   ├── models.py<br>│   ├── tests.py<br>│   └── views.py<br>└── nextjsdrfbackend<br>    ├── asgi.py<br>    ├── __init__.py<br>    ├── secrets.example.py<br>    ├── secrets.py<br>    ├── settings.py<br>    ├── urls.py<br>    └── wsgi.py</pre><pre>3 directories, 15 files</pre><p>Now, we need to modify our rootsettings.py inside the project folder. I usually create a secrets.py file and a secrets.example.py file to keep the secrets (e.g. keys) away from version control, with the second file serving as an example file for those who would be, for example, cloning the repository so that they can set it up properly for themselves. secrets.py , obviously, would therefore be included in the .gitignore file.</p><pre># nextjsdrfbackend/secrets.example.py</pre><pre><strong>DJANGO_SECRET_KEY = &quot;your django secret key&quot;<br>JWT_SECRET_KEY = &quot;your jwt signing secret key&quot;</strong></pre><p>This is our settings.py after all the modifications. Take note of Lines 91, 94 and 95. Be sure to name your custom user model and its corresponding serializer class the same way as you type in here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fQB-TIvr_IjHA6AU1bSatw.png" /><figcaption><strong>backend/nextjsdrfbackend/settings.py</strong></figcaption></figure><p>Now, let’s create our custom user model in nextjsdrfauth/models.py</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rc9vboaRDvGkP3puB_sG4A.png" /><figcaption><strong>backend/nextjsdrfauth/models.py</strong></figcaption></figure><p>And our CustomUserModelSerializer in nextjsdrfauth/serializers.py .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_a5ypOvU0zgshnRhqoo-2A.png" /><figcaption><strong>backend/nextjsdrfauth/serializers.py</strong></figcaption></figure><p>At this point, you can make migrations and create a Django admin/superuser. You can change up the database backend if you want to, but it is not really a concern for this tutorial.</p><pre>$ python manage.py makemigrations<br>Migrations for &#39;nextjsdrfauth&#39;:<br>  nextjsdrfauth/migrations/0001_initial.py<br>    - Create model CustomUserModel</pre><pre>$ python manage.py migrate --run-syncdb<br>Operations to perform:<br>  Synchronize unmigrated apps: allauth, corsheaders, dj_rest_auth, google, messages, registration, rest_framework, staticfiles<br>  Apply all migrations: account, admin, auth, authtoken, contenttypes, nextjsdrfauth, sessions, sites, socialaccount<br>Synchronizing apps without migrations:<br>  Creating tables...<br>    Running deferred SQL...<br>Running migrations:<br>  Applying contenttypes.0001_initial... OK<br>  Applying contenttypes.0002_remove_content_type_name... OK<br>  Applying auth.0001_initial... OK<br>  (...truncated)</pre><pre>$ python manage.py createsuperuser<br>Username: nextjsdrfexample  <br>Email: <a href="/service/mailto:nextjsdrf@xyz.com">nextjsdrfexample@xyz.com</a> <br>Password: <br>Password (again): <br>Superuser created successfully.</pre><p>Now, we would like to wire up the view for our Google Signup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WQcWiQF9cm6DjURGCR8hiA.png" /><figcaption><strong>backend/nextjsdrfauth/views.py</strong></figcaption></figure><p>With the view created that will be used by our frontend application to exchange access_token for the tokens obtained from Google after user authorization, it’s time to wire up the URL endpoints. I prefer having api/* prefix for REST endpoints, but you may use a different scheme if you want to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6NlkJdVaRSFQcpnZMUvndA.png" /><figcaption><strong>urls.py files for the project (top: nextjsdrfbackend) and app (bottom: nextjsdrfauth)</strong></figcaption></figure><p>Lastly, we need to setup the Google application in the admin panel of Django. Before this, head over to the <a href="https://console.developers.google.com/">Google Developer Console</a>, create a new project and generate the OAuth Client ID (namely, CLIENT_ID and CLIENT_SECRET). You may have to add a few test users while in development phase as per Google’s new policies.</p><p><strong>Make sure to choose <em>Web Application</em> as the <em>Application Type </em>and put </strong><strong>https://127.0.0.1:3000/api/auth/callback/google under <em>Authorized redirect URIs </em>section, </strong>since that’s the default URL Next-Auth uses.</p><p>Now, head over to the Django admin and create a new Social Application. Follow the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VV_sXwUGKt4emlls0T7tdA.png" /><figcaption>Creating the new Social application using the OAuth Client ID we just obtained. Make sure to include example.com under the Chosen sites. This will change when you push to production, of course.</figcaption></figure><p>Right now, we are pretty much done with the backend. Now we need to setup the frontend client using Next.js and Next-Auth.</p><h3>Frontend</h3><p>Start by creating a new Next.js app. I will use yarn , but npm works as well. Make sure to have at least the latest LTS version of Node.js installed on your machine. We will also use TypeScript, so I will perform some additional steps pertaining to the TypeScript setup.</p><pre>$ cd next-js-with-drf/client<br>$ yarn create next-app .<br>yarn create v1.22.5<br>[1/4] Resolving packages...<br>[2/4] Fetching packages...<br>[3/4] Linking dependencies...<br>[4/4] Building fresh packages...</pre><pre>(...truncated for brevity)</pre><pre>$ yarn add axios next-auth</pre><pre>$ touch tsconfig.json<br>$ yarn add --dev typescript @types/node @types/react @types/next-auth</pre><p>After this, rename the .js files inside pages folder to .tsx . Now, your client folder should have the following structure. I also deleted the pages/api folder, but we will be recreating it in a bit.</p><pre>$ tree -L 2 .<br>.<br>├── node_modules<br>│   ├── anser<br>│   ├── ansi-regex<br>... (truncated)<br>├── package.json<br>├── pages<br>│   ├── _app.tsx<br>│   └── index.tsx<br>├── public<br>│   ├── favicon.ico<br>│   └── vercel.svg<br>├── README.md<br>├── styles<br>│   ├── globals.css<br>│   └── Home.module.css<br>├── tsconfig.json<br>└── yarn.lock</pre><p>Now, you can start the development server using yarn dev .</p><h3>Setting up .env.local file</h3><p>Create a .env.local file and a .env.example file in the root of the client folder. We will fill the .env.local file with the following information (and add it to .gitignore . The .env.example file will contain the key names so that anyone cloning the repository can know what environment variables are needed to run the application.</p><pre>// .env.local</pre><pre>// would be changed in production<br>NEXTAUTH_URL=http://127.0.0.1:3000</pre><pre>GOOGLE_CLIENT_ID=&lt;client id obtained from Google Developer console&gt;<br>GOOGLE_CLIENT_SECRET=&lt;client secret obtained from Google Developer console&gt;</pre><h3>Setting up the views</h3><p>Replace the contents of pages/index.tsx with the following code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w8NEzavwmejrf_c_2D_hWw.png" /><figcaption><strong>client/pages/index.tsx</strong></figcaption></figure><h3>Setting up Next-Auth</h3><p>Now, we can create pages/api/auth/[...nextauth].ts and add the following code into it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3xS9v2n7TNcOebmQxD21NQ.png" /><figcaption><strong>client/pages/api/auth/[…nextauth].ts</strong></figcaption></figure><p>At this point, you should be able to sign in with your Google account using the frontend application.</p><h3>Intercepting the tokens returned by Google and obtaining access_token from the DRF backend</h3><p>By default, Next-Auth uses the tokens returned by Google to authenticate the user and allow access to protected content on the frontend. But, we want to exchange the tokens obtained with our DRF backend so that we can actually create the user in our database.</p><p>This will be done inside our [...nextauth].ts file, using the methods we specified under thecallbacks object earlier. Replace the code in that file with the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bJDiR4i6KcCe4azOe_0yuw.png" /><figcaption><strong>client/pages/api/auth/[…nextauth].ts after update</strong></figcaption></figure><p>I also created a types.ts file at the root of the client folder and added the following few lines just so that TypeScript knows that I know what I am doing when I modify the user object.</p><pre>import { User } from &quot;next-auth&quot;;</pre><pre>export interface AuthenticatedUser extends User {<br>  accessToken?: string,<br>  refreshToken?: string,<br>}</pre><p>With that set up, you are all done! Head over to your frontend, and now you should be able to sign in with Google. You can also check in your Django admin console that the new user is being correctly created in your database with the custom user model that you specified earlier.</p><h3>Conclusion</h3><p>In this tutorial, we learnt how to consume a DRF API with a Next.js application using Next-Auth. We have only scratched the surface of the things you can do. Now, there are a few caveats. But most important one would be that the access_token from the DRF backend are not being sent as a HttpOnly cookie. Additionally, the DRF endpoint will also send a refresh_token , and there is a DRF endpoint at api/auth/token/refresh/ where you can exchange the refresh_token for a fresh access_token . These are the two things that I would like to explore in a sequel to this post.</p><p>The code will be available at <a href="https://github.com/mahieyin-rahmun/NextJsWithDRFExample">https://github.com/mahieyin-rahmun/NextJsWithDRFExample</a> for anyone who wants to fiddle around with it.</p><p>Also, this is my very first post on medium.com, so I appreciate any feedback on the post itself or the code so that I can make improvements.</p><p>Go beyond!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb4c82be137" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>