Skip to content

Commit af1d710

Browse files
committed
Fix frontend auth requests and set Payload server URL
1 parent 1442b9c commit af1d710

5 files changed

Lines changed: 45 additions & 22 deletions

File tree

src/components/forms/AccountForm/index.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ export const AccountForm: React.FC = () => {
3939
const onSubmit = useCallback(
4040
async (data: FormData) => {
4141
if (user) {
42-
const response = await fetch(`${process.env.NEXT_PUBLIC_SERVER_URL}/api/users/${user.id}`, {
42+
const response = await fetch(`/api/users/${user.id}`, {
4343
// Make sure to include cookies with fetch
4444
body: JSON.stringify(data),
4545
credentials: 'include',

src/components/forms/ForgotPasswordForm/index.tsx

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -24,16 +24,13 @@ export const ForgotPasswordForm: React.FC = () => {
2424
} = useForm<FormData>()
2525

2626
const onSubmit = useCallback(async (data: FormData) => {
27-
const response = await fetch(
28-
`${process.env.NEXT_PUBLIC_SERVER_URL}/api/users/forgot-password`,
29-
{
30-
body: JSON.stringify(data),
31-
headers: {
32-
'Content-Type': 'application/json',
33-
},
34-
method: 'POST',
27+
const response = await fetch('/api/users/forgot-password', {
28+
body: JSON.stringify(data),
29+
headers: {
30+
'Content-Type': 'application/json',
3531
},
36-
)
32+
method: 'POST',
33+
})
3734

3835
if (response.ok) {
3936
setSuccess(true)

src/payload.config.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ const jobsAutoRunEnabled = process.env.PAYLOAD_JOBS_AUTORUN === 'true'
3333
const jobsAutoRunCron = process.env.PAYLOAD_JOBS_AUTORUN_CRON || '* * * * *'
3434

3535
export default buildConfig({
36+
serverURL: getServerSideURL(),
3637
admin: {
3738
meta: {
3839
icons: [

src/providers/Auth/index.tsx

Lines changed: 36 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,32 @@ import type { User } from '@/payload-types'
44

55
import React, { createContext, useCallback, useContext, useEffect, useState } from 'react'
66

7+
const apiPath = (path: string): string => `/api${path.startsWith('/') ? path : `/${path}`}`
8+
9+
const readErrorMessage = async (res: Response, fallback: string): Promise<string> => {
10+
const body = await res.json().catch(() => null)
11+
12+
if (body && typeof body === 'object') {
13+
if (
14+
'errors' in body &&
15+
Array.isArray(body.errors) &&
16+
typeof body.errors[0]?.message === 'string'
17+
) {
18+
return body.errors[0].message
19+
}
20+
21+
if ('message' in body && typeof body.message === 'string') {
22+
return body.message
23+
}
24+
25+
if ('error' in body && typeof body.error === 'string') {
26+
return body.error
27+
}
28+
}
29+
30+
return fallback
31+
}
32+
733
type ResetPassword = (args: {
834
password: string
935
passwordConfirm: string
@@ -39,7 +65,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
3965
const [status, setStatus] = useState<'loggedIn' | 'loggedOut' | undefined>()
4066
const login = useCallback<Login>(async (args) => {
4167
try {
42-
const res = await fetch(`${process.env.NEXT_PUBLIC_SERVER_URL}/api/users/login`, {
68+
const res = await fetch(apiPath('/users/login'), {
4369
body: JSON.stringify({
4470
email: args.email,
4571
password: args.password,
@@ -52,22 +78,21 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
5278
})
5379

5480
if (res.ok) {
55-
const { errors, user } = await res.json()
56-
if (errors) throw new Error(errors[0].message)
81+
const { user } = await res.json()
5782
setUser(user)
5883
setStatus('loggedIn')
5984
return user
6085
}
6186

62-
throw new Error('Invalid login')
63-
} catch {
64-
throw new Error('An error occurred while attempting to login.')
87+
throw new Error(await readErrorMessage(res, `Login failed with status ${res.status}.`))
88+
} catch (error) {
89+
throw new Error(error instanceof Error ? error.message : 'An error occurred while attempting to login.')
6590
}
6691
}, [])
6792

6893
const create = useCallback<Create>(async (args) => {
6994
try {
70-
const res = await fetch(`${process.env.NEXT_PUBLIC_SERVER_URL}/api/storefront/create-account`, {
95+
const res = await fetch(apiPath('/storefront/create-account'), {
7196
body: JSON.stringify({
7297
email: args.email,
7398
password: args.password,
@@ -93,7 +118,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
93118

94119
const logout = useCallback<Logout>(async () => {
95120
try {
96-
const res = await fetch(`${process.env.NEXT_PUBLIC_SERVER_URL}/api/users/logout`, {
121+
const res = await fetch(apiPath('/users/logout'), {
97122
credentials: 'include',
98123
headers: {
99124
'Content-Type': 'application/json',
@@ -115,7 +140,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
115140
useEffect(() => {
116141
const fetchMe = async () => {
117142
try {
118-
const res = await fetch(`${process.env.NEXT_PUBLIC_SERVER_URL}/api/users/me`, {
143+
const res = await fetch(apiPath('/users/me'), {
119144
credentials: 'include',
120145
headers: {
121146
'Content-Type': 'application/json',
@@ -141,7 +166,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
141166

142167
const forgotPassword = useCallback<ForgotPassword>(async (args) => {
143168
try {
144-
const res = await fetch(`${process.env.NEXT_PUBLIC_SERVER_URL}/api/users/forgot-password`, {
169+
const res = await fetch(apiPath('/users/forgot-password'), {
145170
body: JSON.stringify({
146171
email: args.email,
147172
}),
@@ -166,7 +191,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
166191

167192
const resetPassword = useCallback<ResetPassword>(async (args) => {
168193
try {
169-
const res = await fetch(`${process.env.NEXT_PUBLIC_SERVER_URL}/api/users/reset-password`, {
194+
const res = await fetch(apiPath('/users/reset-password'), {
170195
body: JSON.stringify({
171196
password: args.password,
172197
passwordConfirm: args.passwordConfirm,

tsconfig.tsbuildinfo

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

0 commit comments

Comments
 (0)