Next-auth Alternatives

Similar projects and alternatives to next-auth

NOTE: The number of mentions on this list indicates mentions on common posts plus user suggested alternatives. Hence, a higher number means a better next-auth alternative or higher similarity.

Suggest an alternative to next-auth

Reviews and mentions

Posts with mentions or reviews of next-auth. We have used some of these posts to build our list of alternatives and similar projects. The last one was on 2021-11-18.
  • How set dynamic http headers?
    1 project | reddit.com/r/nextjs | 1 Dec 2021
    You can use NextAuth.js if you are looking forward to implement social login on your NextJS project. It has callbacks where you can set custom headers. Next-Auth.js
  • Sveltekit with next auth?
    3 projects | reddit.com/r/sveltejs | 18 Nov 2021
    Then came across this https://github.com/nextauthjs/next-auth/issues/2294 and this https://github.com/wobsoriano/sveltekit-next-auth-demo
  • How to Build a Forum App with NextJs and Strapi CMS
    4 projects | dev.to | 16 Nov 2021
    import React, { useState } from "react"; import style from "../../styles/Home.module.css"; import Link from "next/link"; function Displayforum() { const [show, setShow] = useState(false); return ( Display forum Ask a question Login Questions Posted By: Victory Tuduo Description of the Question Answers Post setShow(!show)}> {show ? "Hide Answers" : "Show Answers"} {show ? (

    Miracle

    Try doing it Like this

    ) : null} ); } export default Displayforum;
    Enter fullscreen mode Exit fullscreen mode

    This component handles the layout of our display forum page. We also have a button here that directs the user to the page to upload new questions.

    Meanwhile, in upload.js we have the following:

        import React from "react";
        import Uploadforum from "./Components/Uploadforum";
        function upload() {
          return (
            
    ); } export default upload;
    Enter fullscreen mode Exit fullscreen mode

    Here, we simply added an import for the Uploadforum component into our page. In Uploadforum.js file we have a simple form to create new questions:

        import React from "react";
        import style from "../../styles/Home.module.css";
        import Link from "next/Link";
        function Uploadforum() {
          return (
            

    Ask a question

    Forum
    Submit Question
    ); } export default Uploadforum;
    Enter fullscreen mode Exit fullscreen mode

    Finally, we have the following styles in Home.module.css

        .container {
          min-height: 100vh;
          padding: 0 0.5rem;
          height: 100vh;
          font-family: monospace;
        }
        /* display forum page */
        .topcont {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 5px 8px;
        }
        .topcont button,
        .inputanswer button,
        .formcont button,
        .showanswer {
          border: none;
          color: #fff;
          background: dodgerblue;
          border-radius: 8px;
          padding: 10px 15px;
          outline: none;
          margin: 8px;
        }
        .topcont button:hover {
          cursor: pointer;
          transform: scale(1.2);
        }
        .heading {
          font-weight: bold;
        }
        .subheading {
          font-weight: 500;
          text-transform: uppercase;
        }
        .userinfo {
          font-size: 18px;
          font-weight: 600;
        }
        .questioncont {
          min-height: 300px;
          padding: 15px 14px;
          box-shadow: 12px 12px 36px rgba(0, 0, 0, 0.12);
        }
        .answercont {
          min-height: 300px;
          padding: 5px 3px 5px 15px;
        }
        .answers {
          height: 300px;
          overflow-x: scroll;
        }
        .inputanswer {
          margin-bottom: 8px;
        }
        .inputanswer textarea {
          width: 100%;
          resize: none;
          padding: 5px 8px;
        }
        .showanswer {
          border: 1px solid dodgerblue;
          background: #fff;
          color: dodgerblue;
          transition: 0.4s ease-in-out;
        }
        .showanswer:hover {
          background: dodgerblue;
          color: #fff;
        }
        .eachanswer {
          border-radius: 15px;
          background: #e7e7e7;
          padding: 8px 15px;
          margin-bottom: 10px;
        }
        .username {
          font-weight: bold;
          text-transform: uppercase;
        }
        .answertext {
          font-family: Montserrat;
          font-size: 14px;
          font-weight: 500;
        }
        /* upload a question page */
        .uploadpage {
          min-height: 100vh;
        }
        .formcont {
          min-width: 100vw;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        .uploadform {
          display: flex;
          flex-direction: column;
          min-width: 500px;
          padding-top: 10px;
        }
        .uploadform input,
        .uploadform textarea {
          resize: none;
          width: 100%;
          margin: 8px;
          padding: 5px;
        }
    
    Enter fullscreen mode Exit fullscreen mode

    All of this makes up the layout of our pages.

    Getting data from Strapi:

    Setting up our Fetch Request

    In this section, we will fetch our data from Strapi and display it in our app. We will be using Axios to perform our fetch operations.

    We will install this via CLI:

        npm install axios
    
    Enter fullscreen mode Exit fullscreen mode

    Create a file index.js in the API folder. Here, we will set up our fetch request:

        import axios from "axios";
        const url = "http://localhost:1337/strapi-forums";
        export const readForum = () => axios.get(url);
        export const createQuestion = (newQuestion) => axios.post(url, newQuestion);
    
    Enter fullscreen mode Exit fullscreen mode

    Above, we added import for axios, the URL to fetch our data, and exported functions to read and create data from our forum.

    We’ll import these functions into our app in our index.js file:

        import { readForum, createQuestion } from "./api";
    
    Enter fullscreen mode Exit fullscreen mode

    Fetching Data from Strapi

    We will fetch the data from Strapi in our index.js file and pass it to Displayforum.js component to display it:

        import { react, useState, useEffect } from "react";
        ...
        const [question, setQuestions] = useState({});
          const [response, setResponse] = useState([]);
          useEffect(() => {
            const fetchData = async () => {
              const result = await readForum();
              setResponse(result.data);
            };
            fetchData();
          }, []);
    
    Enter fullscreen mode Exit fullscreen mode

    Here, we fetched our data from Strapi and assigned it to response with the React useState hook. We have a useEffect function that makes the request when our component mounts.

    Now, we pass this response down to our Displayforum component.

        
    
    Enter fullscreen mode Exit fullscreen mode

    Displaying Data from Strap

    To display our data in our Displayforum.js file, we will map our responses and render our components. Before we do this, we will create two additional text fields in our Strapi CollectionCollection: Username and Answername.

    Back in our Displayforum component we will proceed with displaying our data:

        ...
        function Displayforum({ response }) {
        ...
          {response.map((response, index) => (
          
    ...

    Try doing it Like this

    ) : null}
    ))}
    Enter fullscreen mode Exit fullscreen mode

    Here, we wrapped up our components to map through response and display this component as many times as the number of responses. To display our Strapi data, we simply reference it. We can get our Username with this code:

        response.Username
    
    Enter fullscreen mode Exit fullscreen mode

    We can now add this to our component and display it:

        

    Posted By: {response.Username}

    ...

    {response.Questions}

    ...

    {response.Answername}

    {response.Answers}

    Enter fullscreen mode Exit fullscreen mode

    We have successfully added the data from our CollectionCollection to our front-end to view this in the browser. Run the following command in the CLI:

        npm run dev
    
    Enter fullscreen mode Exit fullscreen mode

    In your browser, you will have an output similar to the image below:

    After this, we will add functionality to add new questions to Strapi.

    Adding data to Strapi

    In our Uploadforum.js file, we will add functionality to upload the contents of the form to Strapi. First, we will create two state variables to store the text from our inputs.

        import { React, useState } from "react";
        ...
        const [name, setName] = useState("");
        const [description, setDescription] = useState("");
    
    Enter fullscreen mode Exit fullscreen mode

    Then we set these variables to the value of our form input.

         setName(e.target.value)}
                  />
                   setDescription(e.target.value)}
                  />
    
    Enter fullscreen mode Exit fullscreen mode

    Also we will a function to send these variables when we click our button.

         sendData()}>Submit Question
    
    Enter fullscreen mode Exit fullscreen mode

    We can create the sendData function above our return.

        const sendData = () => {
          };
    
    Enter fullscreen mode Exit fullscreen mode

    For our create functionality we will import the createQuestion function we defined in our api folder.

        import { createQuestion } from "../api";
    
    Enter fullscreen mode Exit fullscreen mode

    Then we pass in our data to this function.

        const sendData = () => {
            const newQuestion = {
              Title: name,
              Questions: description,
            };
            createQuestion(newQuestion);
          };
    
    Enter fullscreen mode Exit fullscreen mode

    We can now upload new questions to our Strapi collection. We will add the Username when we cover user authentication.

    Next up, we will add functionality to answer questions in our Displayforum component.

    Adding Functionality to Answer Questions

    Since we set a text field for our answers in our collection, it can only take in one value. To have multiple answers for a question, we will delete the Answers field and create another field for our Answers of type json.

    With that done, here is an example of what a response from our API would look like:

    To display our answers, we will map through Answers:

         {response.Answers.map((answers, i) => (
                          

    {response.Answername}

    {answers}

    ))}
    Enter fullscreen mode Exit fullscreen mode

    Now in our browser, if we add more answers to our JSON collection, we can see them displayed on our page.

    Adding New Answers

    We will repeat the same method as we did with our Upload Question functionality for the add answer functionality, but with a minor difference. In your Displayforum component, add the following code:

        import axios from "axios";
        ...
        const [answer, setAnswer] = useState("")
        const [id, setId] = useState("");
        const [a, formerArray] = useState([]);
    
    Enter fullscreen mode Exit fullscreen mode

    We will store the input from the textarea in answer. We will use the id variable to reference the collection we want to add the answer to.

    Then in our form textarea:

          setAnswer(e.target.value)}
                        />
          {
                          setId(response.id);
                          formerArray(response.Answers);
                          submitAnswer()
                        }}>Post
    
    Enter fullscreen mode Exit fullscreen mode

    Then in the submitAnswer function:

        const submitAnswer = () => {
            try {
              axios.put(`http://localhost:1337/forums/${id}`, {
                Answers: [...a, answer],
              });
            } catch (error) {
              console.log(error);
            }
          };
    
    Enter fullscreen mode Exit fullscreen mode

    With this, we can now add answers through our form to our collection.

    User Authentication with NextAuth

    This section will use Nextauth, a NextJs package for authentication, to implement Google login for our application. We will also set up protected routes so that only authenticated users can create questions and view them.

    To install next-auth:

        npm i next-auth
    
    Enter fullscreen mode Exit fullscreen mode

    For our authentication, we will make use of JWT token . JWT is a standard used to create access tokens for an application.

    We will create a file to handle user authentication. To do this, create a folder named auth in your api folder and within it, create a file [...nextauth].js with the following code in it:

        import NextAuth from "next-auth";
        import GoogleProvider from 'next-auth/providers/google'
    
        export default NextAuth({
          providers: [
            GoogleProvider({
              clientId: process.env.GOOGLE_CLIENT_ID,
              clientSecret: process.env.GOOGLE_CLIENT_SECRET,
              authorizationUrl: 'https://accounts.google.com/o/oauth2/v2/auth?prompt=consent&access_type=offline&response_type=code',
            })
          ],
          jwt: {
            encryption: true
          },
          secret: process.env.secret,
          callbacks: {
            async jwt(token, account) {
              if (account ?.accessToken) {
                token.accessToken = account.accessToken
              }
              return token;
            },
            redirect: async (url, _baseUrl)=>{
              if (url === '/check') {
                return Promise.resolve('/')
              }
              return  Promise.resolve('/')
            }
        }
        });
    
    Enter fullscreen mode Exit fullscreen mode

    The code above sets up our Google Authentication for our app. To use it, we need to wrap up our application in _app.js with the Google Provider component:

        ...
        import {Provider} from 'next-auth/client'
        function MyApp({ Component, pageProps }) {
          return (
            
              
            
          );
        }
        export default MyApp;
    
    Enter fullscreen mode Exit fullscreen mode

    Next, we will modify our Displayforum component in to return to our component if the user is authenticated, else it returns a button that leads to an authentication page:

        import {signIn, signOut, useSession} from 'next-auth/client'
        ...
        const [session, loadingSession] = useSession();
    
    Enter fullscreen mode Exit fullscreen mode

    We will use useSession to know if our user has been authorized.

        if (loadingSession) {
            <>
              

    logging in

    >; } return( ...
    Enter fullscreen mode Exit fullscreen mode

    The above code simply returns “logging in” if loadingSession is true. If there is session, we will return the rest of the component and if there is no session we will render a button to sign in to access the app.

        return(
        
    {!session && ( <>

    Sign in to access forum

    signIn()}>Sign In > )} {session && ( <> {/*rest of our app*/} > )}
    Enter fullscreen mode Exit fullscreen mode

    We will also set our button to Sign out:

        ...
        
          Ask a question
        
         signOut()}>Signout
        ...
    
    Enter fullscreen mode Exit fullscreen mode

    To make use of Google authentication in our app, we will require access credentials from Google Cloud console. To get this, navigate in your browser to Google Cloud.

    Click on OAuth Client ID and Fill out the fields on the new page that opens.

    Finally, set the redirect URL to: http://localhost/api/auth/callback/google

    To use the credentials in the […nextauth].js file, you can create a .env file and set up your environmental variables:

        GOOGLE_CLIENT_ID: id
        GOOGLE_CLIENT_SECRET: secret
        secret: any string
    
    Enter fullscreen mode Exit fullscreen mode

    Next, we will set up our Uploadforum.js component on our upload page as a protected route so that unauthorized users can’t access the route. To do this, in upload.js add the following code:

        import { getSession, useSession } from 'next-auth/client'
    
    Enter fullscreen mode Exit fullscreen mode

    Then at the bottom:

        export async function getServerSideProps(context) {
          const session = await getSession(context);
          if (!session) {
            context.res.writeHead(302, { Location: '/' });
            context.res.end();
            return {};
          }
          return {
            props: {
              user: session.user,
            }
          }
        }
        export default Upload;
    
    Enter fullscreen mode Exit fullscreen mode

    Now, if you run the app with npm run dev in CLI, we have Google authentication implemented. Also we can’t access the /upload path without logging in.

    Adding User name to Collection

    Now that we have added authentication to our app, we can add the username received from the Google Login as the Answername field when we answer a question:

        ...
         axios.put(`http://localhost:1337/forums/${id}`, {
                Answers: [...a, answer],
                Answername: session.user.name,
              });
    
    Enter fullscreen mode Exit fullscreen mode

    Now, if I add a new answer to the form:

    When I click on the Post button, I get:

    The answer has been added and the Answername field has been set to my user.name form our session.

    Finally, we will also add the username when posting a question to our collection. We will do this in our upload.js file:

         const [session, loadingSession] = useSession();
    
    Enter fullscreen mode Exit fullscreen mode

    Then we pass the value of session to our Uploadforum Component:

        
    
    Enter fullscreen mode Exit fullscreen mode

    We can now use session data in our Uploadforum component:

        function Uploadforum({session}) {
        ...
         const newQuestion = {
              Title: name,
              Questions: description,
              Answers: [""],
              Username: session.user.name,
            };
    
    Enter fullscreen mode Exit fullscreen mode

    Any new questions added now take the Username field to be the username received from session.

    If we add new answers, since the Answername is a field, it overwrites the previous data and all the answers use the same name. To fix this, we will simply modify our Answers field of type JSON to contain both the answers and the username of the person providing the answers.

    Then, we can get this data and display it in our Displayforum component:

         
    {response.Answers.map((answers, i) => (

    {answers[0]}

    {answers[1]}

    ))}
    Enter fullscreen mode Exit fullscreen mode

    answer[0] is the name of the user, while answers[1] is the answer.

    Finally, we will modify the code to add new answers:

        ...
         axios.put(`http://localhost:1337/forums/${id}`, {
                Answers: [...a, [session.user.name, answer]],
              });
            } catch (error) {
              console.log(error);
    
    Enter fullscreen mode Exit fullscreen mode

    We can now add new answers to our questions without overwriting previous data.

    When I click on post I get a new answer:

    Conclusion

    We have come to the end of this tutorial. In this tutorial, we learned how to use Strapi CMS and connect it to NextJ's front-end. In this process, we built a forum site and implemented user authentication and authorization on it.

    Resources

    The source code used in this tutorial can be found in the GitHub repo: Forum Application.

  • Help with large Wordpress site (170k products)
    1 project | reddit.com/r/Wordpress | 3 Nov 2021
    From there, you have to figure out things like Auth, API integrations, SSR, etc. With sveltekit, you're basically starting from Scratch because it's still in beta. Next/Gatsby/Nuxt have more developed eco systems and you can use packages like https://next-auth.js.org/ for authentication.
  • Securing my app
    2 projects | reddit.com/r/nextjs | 2 Nov 2021
    NextAuth has a Firebase Adaptor but I haven't used it myself (I've only used NextAuth w/ Auth0).
  • Adding email/password Supabase auth to a Nextjs app
    4 projects | reddit.com/r/nextjs | 22 Oct 2021
    Is Supabase auth something you dedicatedly want? If not, you should check out next-auth.js
  • `account.access_token` &amp; `account.refresh_token` is `undefined` when using Twitter Provider with `next-auth`?
    3 projects | reddit.com/r/nextjs | 16 Oct 2021
    I am following this tutorial & am unable to get the value of access_token & refresh_token from next-auth. My callback function looks like:
  • Nextjs with Firebase
    2 projects | reddit.com/r/nextjs | 6 Oct 2021
    In the SSR case, if all you want is firestore, then the admin SDK is perfect for this and easy enough to use from the server-side. If you want authentication also, that adds some moving pieces and I would probably at next-firebase-auth (which works with firebase authentication) or next-auth (which can use firestore for it's database, but handles authentication itself) to take care of the heavy lifting of SSR authentication.
  • Best way to check if a user is authenticated to view page?
    1 project | reddit.com/r/nextjs | 28 Sep 2021
    I use next-auth and my checking code for protected pages is:
  • Does anyone know a open-source nextjs production repo?
    6 projects | reddit.com/r/nextjs | 23 Sep 2021
  • Not able to get the value of the session on my API route
    1 project | reddit.com/r/nextjs | 6 Sep 2021
    https://github.com/nextauthjs/next-auth/issues/631 answer by readywater himself helped.
  • Gradient.art - Designing and Inspecting Complex CSS Gradients
    5 projects | dev.to | 2 Sep 2021
    NextAuth.js
  • A little lost in how to link Next, Apollo Server/GraphQL, Postgres, and custom auth without a service
    2 projects | reddit.com/r/webdev | 1 Sep 2021
    I use this: https://next-auth.js.org with the same stack you're describing. Works well.
  • Apollo Client and Server with Next.js and auth0
    1 project | reddit.com/r/graphql | 12 Aug 2021
  • Help using the Next-Auth TypeORM model/adapter?
    2 projects | reddit.com/r/nextjs | 5 Aug 2021
    I'm working on an application using next-auth with MongoDB. I'm having a lot of trouble figuring out how to access the TypeORM models or adapters so I can manipulate the User documents according to the schema. Currently I just created a new connection to my Mongo DB and was able to manipulate my User record from there but it allowed me to add arbitrary fields and not follow types because I wasn't using TypeORM just 'vanilla' Mongo. Can someone point me in the right direction on how to access the TypeORM adapter in Next API routes so I can do this the right way?

Stats

Basic next-auth repo stats
54
8,206
9.3
2 days ago

nextauthjs/next-auth is an open source project licensed under ISC License which is an OSI approved license.

SaaSHub - Software Alternatives and Reviews
SaaSHub helps you find the best software and product alternatives
www.saashub.com
Find remote JavaScript jobs at our new job board 99remotejobs.com. There are 16 new remote jobs listed recently.
Are you hiring? Post a new remote job listing for free.