Next.js Discord

Discord Forum

Server Actions

Answered
Virtue posted this in #help-forum
Open in Discord
Hello, I am exporting a server action for a client component, but I am getting an error.

"You're importing a component that needs next/headers. That only works in a Server Component which is not supported in the pages/ directory. Read more: https:/ /nextjs.org/docs/getting-started/"

by the way I'm using an app router, but the error says pages/ is not supported

The way I solved the problem was to add "use server" to auth.js, but how correct is it or is it safe for secret? I have not received such an error before.

signup.js
"use client";

import { useFormStatus, useFormState } from "react-dom";
import { signup } from "@/actions/auth";


auth.js

"use server";
import { SignupFormSchema } from '@/lib/definitions'
import { createSession } from '@/lib/session'


session.js

import 'server-only'
import { SignJWT, jwtVerify } from 'jose'
import { cookies } from 'next/headers'

const secretKey = process.env.SESSION_SECRET
const encodedKey = new TextEncoder().encode(secretKey)
Answered by joulev
Without that use server, your signup() logic is run entirely on the client, which means nextjs needs to run cookies() on the client which doesn’t work.

By adding use server, you tell nextjs that signup() needs to be run on the server instead. On the server, cookies() works, so that’s why you need to add the use server directive.
View full answer

5 Replies

Australian Freshwater Crocodile
Server actions starts with “use server” not “use server-only”
session.js
Answer
It is safe for secrets and it most likely is safe overall. Just ensure that the async functions exported from that use server file doesn’t return anything sensitive, like return process.env.SESSION_SECRET