Next.js Discord

Discord Forum

server actions called multiple times + not setted cookies

Unanswered
Argentine ant posted this in #help-forum
Open in Discord
Argentine antOP
Guys I have easy login to admin
export const login = async (login: FormDataEntryValue | null, password: FormDataEntryValue | null) => {
    if (login !== 'login' || password !== 'password') return { message: 'bad' }
    const session = await encrypt({ login, password })
    cookies().set('session', session, { expires: new Date().getTime() + 1000 * 60 * 60 * 24 * 7 })
    revalidatePath('/', 'layout')
    return { message: 'success' }
}

export const verifyCookie = async (): Promise<boolean> => {
    const admin = cookies().get('session')
    console.log('admin?.value', admin?.value)
    if (admin === undefined) return false
    const value: JWTPayload = await decrypt(admin.value)
    return value.password === 'password'
}


export const encrypt = async (payload: { login: string; password: string }) => {
    return await new SignJWT(payload).setProtectedHeader({ alg: 'HS256' }).setIssuedAt().sign(key)
}

export const decrypt = async (arg: string) => {
    const { payload } = await jwtVerify(arg, key, { algorithms: ['HS256'] })
    return payload
}
export const logout = async () => {
    cookies().delete('session')
    revalidatePath('/', 'layout')
    return { message: 'success' }
}


In my admin layout
export default async function AdminLayout({ children }: { children: ReactNode }) {
    const bool = await verifyCookie()
    if (!bool) return redirect('/admin/login')
    return (
        <section>
            <AuthLayout>{children}</AuthLayout>
        </section>
    )
}

Problem is,
My cookies not setted in browser (didnt see it) but if I logged cookies, in FIRST page in my admin I see cookies value (4x IDK why 4x this value) but after click to another page, cookies is undefined.

2 Replies

Argentine antOP
my middleware
import createIntlMiddleware from 'next-intl/middleware'
import { NextRequest } from 'next/server'

const locales = ['en']
const defaultLocale = locales[0]

export default async function middleware(request: NextRequest) {
    const langCookie = request.cookies.get('lang')
    let currentLocale = langCookie !== undefined ? langCookie.value : defaultLocale
    if (locales.includes(defaultLocale)) {
        currentLocale = defaultLocale
    }
    // Step 2: Create and call the next-intl middleware (example)
    const handleI18nRouting = createIntlMiddleware({
        locales,
        defaultLocale,
    })
    const response = handleI18nRouting(request)

    // Step 3: Alter the response (example)
    response.cookies.set('lang', currentLocale)
    return response
}
export const config = {
    matcher: ['/((?!_next|api|favicon.ico|robots.txt|sitemap.xml|manifest.json|sw.js|ios|android|images|fonts|ios).*)'],
}
Argentine antOP
ok it was this manipulation with cookies in middleware