How do I authenticate a React or Next.js app using REST or GraphQL? #1902
jacobsfletch
started this conversation in
Show and tell
Replies: 2 comments
-
Related: https://github.com/payloadcms/next-auth-frontend |
Beta Was this translation helpful? Give feedback.
0 replies
-
If you are using the GraphQL API, here's the same import React, { useState, createContext, useContext, useEffect, useCallback } from 'react'
import { User } from '../../payload-types'
type Login = (args: { email: string; password: string }) => Promise<void>
type Logout = () => Promise<void>
type AuthContext = {
user?: User | null
setUser: (user: User | null) => void
logout: Logout
login: Login
}
const Context = createContext({} as AuthContext)
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [user, setUser] = useState<User | null>()
const login = useCallback<Login>(async args => {
const res = await fetch(`${process.env.NEXT_PUBLIC_CMS_URL}/api/graphql`, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: `mutation {
loginUser(email: "${args.email}", password: "${args.password}") {
user {
email
}
exp
}
}`,
}),
})
if (res.ok) {
const { data, errors } = await res.json()
if (errors) throw new Error(errors[0].message)
setUser(data?.loginUser?.user)
} else {
throw new Error('Invalid login')
}
}, [])
const logout = useCallback<Logout>(async () => {
const res = await fetch(`${process.env.NEXT_PUBLIC_CMS_URL}/api/graphql`, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: `mutation {
logoutUser
}`,
}),
})
if (res.ok) {
setUser(null)
} else {
throw new Error('There was a problem while logging out.')
}
}, [])
useEffect(() => {
const fetchMe = async () => {
const res = await fetch(`${process.env.NEXT_PUBLIC_CMS_URL}/api/graphql`, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: `query {
meUser {
user {
email
}
exp
}
}`,
}),
})
if (res.ok) {
const { data } = await res.json()
setUser(data?.meUser?.user || null)
} else {
throw new Error('There was a problem while logging out.')
}
}
fetchMe()
}, [])
return (
<Context.Provider
value={{
user,
setUser,
login,
logout,
}}
>
{children}
</Context.Provider>
)
}
type UseAuth<T = User> = () => AuthContext
export const useAuth: UseAuth = () => useContext(Context) |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Authenticating with Payload from a React or Next.js app is quite straightforward. To do this, wrap your entire app with this
AuthProvider
. It will provide theuseAuth
hook that you can use to easily perform any auth operation from anywhere in your app:Initialize the provider by wrapping your entire app like this:
Now you can fire the
useAuth
hook in any component of your app. Logging in, for instance, might look like this:Once authenticated, the
user
property will be populated in the auth context.Beta Was this translation helpful? Give feedback.
All reactions