Replies: 5 comments 3 replies
-
Could someone post some pointers to a solution/tutorial/guide here please? |
Beta Was this translation helpful? Give feedback.
-
Yes, it is possible (as documented by docs). On a recent project I had a similar requirement, where the next.js API serves both the authentication of the site itself and of a react native app. The basic idea was to check the session endpoint to validate whether the user is authenticated and have 2 functions that do the sign in/out. The functions look something like this: const signIn = async (credentials) => {
return fetch(`${basePath}/api/auth/csrf`)
.then(r => r.json())
.then(({ csrfToken }) =>
fetch(`${basePath}/api/auth/callback/credentials`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ...credentials, csrfToken, json: "true" }),
})
)
}
const signOut = async () => {
return fetch(`${basePath}/api/auth/csrf`)
.then(r => r.json())
.then(({ csrfToken }) =>
fetch(`${basePath}/api/auth/signout`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ csrfToken, json: "true" }),
})
)
} You may also take inspiration from https://github.com/nextauthjs/next-auth/blob/main/packages/next-auth/src/react/index.tsx#L212 |
Beta Was this translation helpful? Give feedback.
-
Thank you @Dragate! That was very helpful. Just like the original poster I am working on an API-only application. In my case it's not a NextJs one but a more barebones NodeJs script. Because my code is not running in the browser I had some more hurdles to take. For anyone in the future attempting to do the same I will post a list of facts, opinions (my own traps), and though processes.
Happy sailing with this great library from now on! 👍 |
Beta Was this translation helpful? Give feedback.
-
next-auth doc is awful |
Beta Was this translation helpful? Give feedback.
-
What I did was a I built an custom endpoint for 3rd party applications, using the same credentials from the database, but practically no next-auth |
Beta Was this translation helpful? Give feedback.
-
Question 💬
We are creating an API-only application, means that there is no UI, if we use the Credentials provider, is it possible to sign in a user with a REST API call and then get a token back?
How to reproduce ☕️
Create an API-only Next.js application and use NextAuth.js for authentication.
Contributing 🙌🏽
Yes, I am willing to help answer this question in a PR
Beta Was this translation helpful? Give feedback.
All reactions