User Authentication with Next.js and Strapi

In this tutorial, we'll be building a Next.js application and authenticate that with Strapi and NextAuth.


This is a companion discussion topic for the original entry at https://strapi.io/blog/user-authentication-in-next-js-with-strapi

After clicking Sign In button:

Error: HTTP GET is not supported for /api/auth/error

2 Likes

@Nirmalay Ghosh
Thanks for putting this together.

Is there a way to integrate NextAuth into NextJS without needing to supply the Database connection? Database is already interfaced with Strapi. Otherwise what is Strapi for?

database: process.env.NEXT_PUBLIC_DATABASE_URL,

Also, shouldn’t that be a private variable, not public?

I just tested leaving out the database field completely, and it works. The newly created user profile is visible in Strapi.

It would be great to extend this blog with adding Auth0 as well given the different use cases. The other Auth0/Strapi blog uses a different mechanism to connect which doesn’t seem to fit with NextJS/NextAuth

FYI these are for NextAuth@3. Default next will use v4 now and a bit has changed.

2 Likes

should the request URL be with api/ prefix?

const response = await fetch(
          `${process.env.NEXT_PUBLIC_API_URL}/auth/${account.provider}/callback?access_token=${account?.accessToken}`
        );

if so, why does the endpoint responds with UnauthorizedError ?

 data:  {
   data: null,
  error: {
     status: 401,
     name: 'UnauthorizedError',
    message: 'Missing or invalid credentials',
     details: {}
   }
}

if not, why does the endpoint respond with NotFoundError ?

 data:  {
   data: null,
   error: {
     status: 404,
     name: 'NotFoundError',
    message: 'Not Found',
     details: {}
]   }
 }

PD: I’m using the version: “@strapi/strapi”: “^4.0.0”,

thanks in advance! :wink:

2 Likes

TY… Just figured this out after struggling to get this to work in strapi v4 for whole day today.

It may help someone in future. In V4, we need to call /api/connect/google and NOT /connect/google and also have to use /api/connect/google/callback in google developer console as valid callback url.

Still stuck with the next step. Google now gives a token. But this token seem to fail with
{“data”:null,“error”:{“status”:401,“name”:“UnauthorizedError”,“message”:“Missing or invalid credentials”,“details”:{}}}

Request is going to /api/auth/google/callback?id_token={tokenId}. Any idea how to move forward from this? Google auth has been setup with basic scopes and no restricted scopes. so, that may not be the problem.

Thanks and Regards
M

3 Likes

I’m curious why auth libraray doesn’t consume providers info in strapi rather than reading .env. Do you know any wrapper of nextauth for this?

This is another example using Email provider

1 Like

Have you figured out how to make it pass the 401?

Thanks mate.

1 Like

Are there any updates on using NextAuth with Strapi v4 because I can’t make working solution for this setup?

With regards

There is an open issue about external providers with v4, currently 4.0.4 has the same issue.

I tested the strapi’s local provider in /api/auth/local works normally, I’ll use this in my project with next-auth and comment the google provider until this is fixed, thanks @ivanandresdiaz :grinning:

2 Likes

I had to download the 3 version of NextAuth, and it worked

I cannot seem to get the auth to write to the strapi DB. I can connect, but it doesn’t create a new entry.

[…nextauth.js]

import NextAuth from "next-auth"
import DiscordProvider from "next-auth/providers/discord"

export default NextAuth({
  // Configure one or more authentication providers
  providers: [
    DiscordProvider({
      clientId: process.env.DISCORD_CLIENT_ID,
      clientSecret: process.env.DISCORD_CLIENT_SECRET
    })
  ],
})

Discord callback
http://localhost:3000/api/auth/callback/discord

Strapi callback
http://localhost:3000/api/auth/callback/discord

Should this not be enough to get an entry in Strapi?

Hi Nirmalya,

Does strapi support Back end .I was thinking only as Headless CMS.

Could you explain ,if we can further extend this like After Login Authentication and have form inputs which we can update to Strapi DB,

I am ever much new .I would like to contribute on this.

Harish

Sorry I cannot get this working with next-auth 4 and strapi 4.

${process.env.NEXT_PUBLIC_API_URL}/auth/${account.provider}/callback?access_token=${account?.accessToken}

this link gives only 404 json response.
Btw since my provider is not listed, and it support cas, so i’m using cas from strapi provider.

and from the pr that closed the issue mentioned above, they removes the possibility to authenticate requests using access_token url query param. So this /auth/provider/callback?access_token is not going to work by design for latest version, right?

If so, what is the current method to use provider auth?

1 Like

If you want this to work you need to change account?.accessToken to account?.access_token

1 Like

The docker-compose.yml file refers to image strapi/strapi and looking at the tags there does not seem to be an official v4 image available yet?

1 Like