How to use NextAuth.js with Strapi? #574
-
|
Please refer to the documentation, the example project and existing issues before creating a new issue. Configure using Strapi ?? What are you trying to do |
Beta Was this translation helpful? Give feedback.
Replies: 10 comments 39 replies
-
|
Hi there! This has come up before in #474 #276 and #411. tl;dr This is a good question to ask the Strapi folks about. It's commercial software and they have a larger team so are better placed to be a starting point to ask about this. From what I understand, Strapi has it's own authentication system but it seems NextAuth.js might be a really good fit for it the built-in authentication system isn't as full featured (as it's not a primary selling point). I think it should be able to integrate them and we just need an example and/or tutorial we can point folks to. I'm really happy to collaborate with folks from Strapi if they want to get in touch. |
Beta Was this translation helpful? Give feedback.
-
|
I hope they will give positive response #7477 |
Beta Was this translation helpful? Give feedback.
-
|
They just published this on strapi blog https://strapi.io/blog/user-authentication-in-next-js-with-strapi |
Beta Was this translation helpful? Give feedback.
-
|
I was wondering if registering with next-auth and for example the Twitter provider if it is possible to also create a user in Strapi? The login works fine with next-auth but it does not create a user in the strapi. |
Beta Was this translation helpful? Give feedback.
-
|
How do you connect then to your strapi database? Can you maybe show this
part of your code?
Op wo 7 apr. 2021 om 08:56 schreef Vadim Korolev ***@***.***>:
… I have one database for nextauth and strapi backend. In it there are 3
entity: accounts for third party providers, users for email nextauth
provider and users-permissions_user for strapi users. I blocked modify
userdata permissions via admin panel for content-managers.
If you need option to edit programmatically user emails in account you can
create triggers for db on change data, but i think it's not good practice
in this case
—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
<#574 (reply in thread)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/ACTLWC65JH5QSM5TVDJYRCDTHP6Z3ANCNFSM4V2YRV6Q>
.
|
Beta Was this translation helpful? Give feedback.
-
|
i wonder next-auth save credentials in cookies but strapi return jwt in response, so how can strapi understand authenticaion each request. |
Beta Was this translation helpful? Give feedback.
-
|
Hi all, anyone has found a better solution for implementing next-auth passwordless with strapi? Have one db with multiple versions of the same user object (one in |
Beta Was this translation helpful? Give feedback.
-
|
Hi, I was using Strapi for authentication with next-auth, but I decided to go with a completely different approach. Instead of relying on Strapi for authentication, I only use Strapi data model, which was extended, for user and account storage. The solution relies on a next auth adapter that uses prisma to connect to strapi database. Strapi then is not used to mediate the authentication. Strapi model`{ { { Prisma model`generator client { generator docs { datasource db { model accounts { /// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by the Prisma Client. model sessions { @@unique([sessionToken]) /// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by the Prisma Client. model up_users { @@index([created_by_id], map: "up_users_created_by_id_fk") model verification_tokens { @@index([created_by_id], map: "verification_tokens_created_by_id_fk") ` Adapter:`import { PrismaClient } from '@prisma/client';
nextauth options`import NextAuth from 'next-auth'; const prisma = new PrismaClient({ export const authOptions = { } const Auth = (req, res) => NextAuth(req, res, authOptions); export default Auth; ` |
Beta Was this translation helpful? Give feedback.
-
|
After testing different examples, tutorials, and posts around the web, I finally came up with a solution. SessionProviderInside for NextAuth v4: import { SessionProvider } from "next-auth/react";
function MyApp({ Component, pageProps: { session, ...pageProps }}) {
return (
<SessionProvider session={session}>
<Component {...pageProps} />
</SessionProvider>
);
}
export default MyAppfor NextAuth v3: import { Provider } from 'next-auth/client'
function MyApp({ Component, pageProps: { session, ...pageProps }}) {
return (
<Provider session={session}>
<Component {...pageProps} />
</Provider>
);
}
export default MyAppEnvironment VariablesCreate You may want to generate a secret using openssl (you can use cryptool.org online terminal if you don't have openssl on your machine) $ openssl rand -base64 32NextAuth ConfigCreate import axios from "axios";
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
export default NextAuth({
// the secret is required, otherwise you will face 'JWEDecryptionFailed' error
secret: process.env.NEXTAUTH_SECRET,
// Configure one or more authentication providers
providers: [
CredentialsProvider({
name: "Sign in with Email",
credentials: {
email: { label: "Email", type: "text" },
password: { label: "Password", type: "password" },
},
async authorize(credentials, req) {
// return (
/**
* This function is used to define if the user is authenticated or not.
* If authenticated, the function should return an object contains the user data.
* If not, the function should return `null`.
*/
if (credentials == null) return null;
/**
* credentials is defined in the config above.
* We can expect it contains two properties: `email` and `password`
*/
// using axios is recommended but optional. You can use native fetch() or other libraries.
try {
const { user, jwt } =
(await axios
.post(`${process.env.STRAPI_URL}/api/auth/local`, {
identifier: credentials.email, /* identifier can be the username, instead of the email */
password: credentials.password,
})
.then((response) => {
return response.data;
})
.catch((error) => {
console.log(error.response);
throw new Error(error.response.data.message);
})) || null;
return { jwt, ...user };
} catch (error) {
console.warn(error);
// Sign In Fail
// return null;
}
// );
},
}),
],
callbacks: {
jwt: async ({ token, user }) => {
if (user) {
token.id = user.id;
token.jwt = user.jwt;
token.username = user.username; /* ### */
}
return Promise.resolve(token);
},
session: async ({ session, token }) => {
session.id = token.id;
session.jwt = token.jwt;
session.user.username = token.username; /* ### */
return Promise.resolve(session);
},
},
});To add additional fields (returned from Strapi) to your Custom Sign-in pageCreate a new js file in import { signIn } from "next-auth/react";
import { useRouter } from "next/router";
export default function SignIn() {
const router = useRouter();
const onSubmit = async (e) => {
e.preventDefault();
signIn("credentials", {
email: e.target.email.value,
password: e.target.password.value,
redirect: false,
}).then(({ ok, error }) => {
if (ok) {
router.push("/profile");
} else {
console.warn("error: ", error);
}
});
};
return (
<form onSubmit={onSubmit}>
<input id="email" name="email" type="text" />
<input id="password" name="password" type="password" />
<button>Sign In</button>
</form>
);
}Check Sessionimport { useSession } from "next-auth/react";
import { useEffect } from "react";
export default function Home() {
const { data: session } = useSession();
useEffect(() => {
console.log(session);
}, [session]);
/* rest of your code ... */Resources:
|
Beta Was this translation helpful? Give feedback.
-
|
Hi ShahriarKh, thanks for the code, it works perfectly. I only have one small detail, when it returns the user information when logging in, I only get the username, email and name data, the rest of the data in the user's strapi is not shown, what could it be? thank you! |
Beta Was this translation helpful? Give feedback.

They just published this on strapi blog
https://strapi.io/blog/user-authentication-in-next-js-with-strapi