Receiving cookies from requests made by server-actions
Unanswered
Sloth bear posted this in #help-forum
Sloth bearOP
I am making a request to my backend, sending the user's login data, and the backend returns the session cookie to me through the headers. However, the front-end only sets the cookie in requests outside of server-actions.
-# app/actions.tsx
-# @/http/authenticate-with-password
-# app/actions.tsx
'use server'
import { z } from 'zod'
import { signInWithPassword } from './http/authenticate-with-password'
const loginSchema = z.object({
email: z.string().email(),
password: z.string().min(6),
})
export async function login(_: unknown, formData: FormData) {
const result = loginSchema.safeParse(Object.fromEntries(formData))
if (!result.success) {
console.log(result.error.flatten())
return result.error.flatten().fieldErrors.email?.[0]
}
const { email, password } = result.data
try {
await signInWithPassword({
email,
password,
})
return 'Successfully logged in.'
} catch (error) {
console.error(error)
return 'An error occurred, please try again.'
}
}-# @/http/authenticate-with-password
import { api } from './api-client'
interface SignInWithPasswordRequest {
email: string
password: string
}
interface SignInWithPasswordResponse {
user: {
id: string
email: string | null
password: string | null
}
session: {
id: string
expiresAt: Date
fresh: boolean
userId: string
}
}
export async function signInWithPassword({
email,
password,
}: SignInWithPasswordRequest): Promise<SignInWithPasswordResponse> {
const result = await api
.post('sessions/password', {
json: {
email,
password,
},
})
.json<SignInWithPasswordResponse>()
return result
}1 Reply
Sloth bearOP
-# app/page.tsx
'use client'
import { useActionState } from 'react'
import { login } from '@/actions'
export default function Home() {
const [state, loginAction, isPending] = useActionState(login, '')
return (
<form>
{/* form logic */}
</form>
)
}