Is it currently possible to use clerk auth with NextJS' 13.4 server actions?

I know it's currently in alpha, but I'd like to know if there is any way to use it right now. Library versions are the latest.
@acme/nextjs:dev: - error Error: Clerk: auth() and currentUser() are only supported in App Router (/app directory).
@acme/nextjs:dev: If you're using /pages, try getAuth() instead.
@acme/nextjs:dev: Original error: Error: Invariant: Method expects to have requestAsyncStorage, none available
@acme/nextjs:dev: at handleUpdateNoteContents (./src/app/@modal/(.)e/[id]/actions.ts:13:82)
@acme/nextjs:dev: - error Error: Clerk: auth() and currentUser() are only supported in App Router (/app directory).
@acme/nextjs:dev: If you're using /pages, try getAuth() instead.
@acme/nextjs:dev: Original error: Error: Invariant: Method expects to have requestAsyncStorage, none available
@acme/nextjs:dev: at handleUpdateNoteContents (./src/app/@modal/(.)e/[id]/actions.ts:13:82)
// actions.ts
"use server";

import { currentUser } from "@clerk/nextjs";

import { db } from "@acme/db";

export const handleUpdateNoteContents = async (id: string, content: string) => {
const user = await currentUser();
if (!user) {
return {
error: "You must be logged in to update a note",
};
}
const { id: userId } = user;
await db
.updateTable("Note")
.set({
content,
})
.where(({ and, cmpr }) =>
and([cmpr("id", "=", id), cmpr("userId", "=", userId)]),
)
.executeTakeFirstOrThrow();
};
// actions.ts
"use server";

import { currentUser } from "@clerk/nextjs";

import { db } from "@acme/db";

export const handleUpdateNoteContents = async (id: string, content: string) => {
const user = await currentUser();
if (!user) {
return {
error: "You must be logged in to update a note",
};
}
const { id: userId } = user;
await db
.updateTable("Note")
.set({
content,
})
.where(({ and, cmpr }) =>
and([cmpr("id", "=", id), cmpr("userId", "=", userId)]),
)
.executeTakeFirstOrThrow();
};
// page.tsx
'use client'
// ...
export default function EditNoteModal({ params }: { params: { id?: string } }) {
const [isPending, startTransition] = useTransition();
// ...
const router = useRouter();
// ..
const updateContent = ({ content }: EditFormData) => {
const add = async () =>
startTransition(() => {
handleUpdateNoteContents(params.id!, content);
});

reset();
add()
.then(() => {
router.refresh();
router.back();
})
.catch((err) => console.error(err));
};
//...
}
// page.tsx
'use client'
// ...
export default function EditNoteModal({ params }: { params: { id?: string } }) {
const [isPending, startTransition] = useTransition();
// ...
const router = useRouter();
// ..
const updateContent = ({ content }: EditFormData) => {
const add = async () =>
startTransition(() => {
handleUpdateNoteContents(params.id!, content);
});

reset();
add()
.then(() => {
router.refresh();
router.back();
})
.catch((err) => console.error(err));
};
//...
}
I
inselbegabter•368d ago
I feel like @James Perkins knows a lot about clerk 😄
JP
James Perkins•368d ago
I know too much about Clerk.
I
inselbegabter•368d ago
hahahaha
JP
James Perkins•368d ago
So there is a bug in Next.js that causes this problem. 🙂 Which hasn't been fixed by them yet, we reported it like 2 months ago or so. But it can still be used, just gotta dig it up
I
inselbegabter•368d ago
Thats good to know! I was going crazy already. Thank you for your reply 🙂 Really? I'd love to know how 😄
JP
James Perkins•368d ago
So I think I remember correctly. you need to import auth() on the page that the action is also happening. So for example, this should work as a server action. even though it's all on one page:
import { auth, currentUser } from '@clerk/nextjs';

export default function AddToCart() {
async function addItem(data: any) {
'use server';
console.log(auth().userId);
console.log((await currentUser())?.firstName);
console.log('add item server action', data);
}

return (
// @ts-ignore
<form action={addItem}>
<input
value={'test'}
type='text'
name='name'
/>
<button type='submit'>Add to Cart</button>
</form>
);
}
import { auth, currentUser } from '@clerk/nextjs';

export default function AddToCart() {
async function addItem(data: any) {
'use server';
console.log(auth().userId);
console.log((await currentUser())?.firstName);
console.log('add item server action', data);
}

return (
// @ts-ignore
<form action={addItem}>
<input
value={'test'}
type='text'
name='name'
/>
<button type='submit'>Add to Cart</button>
</form>
);
}
I
inselbegabter•368d ago
I'll try it and let you know it it works. Thanks James!
JP
James Perkins•368d ago
Yeah, it may or may not work it's very much a early early alpha a lot of usage seems to break even though it should work
I
inselbegabter•368d ago
When adding your server actions to a actions.ts file, it doesn't work. I like to use this pattern, bc it allows me to use the server actions in a client component. When using clerk in a pure server component, I don't need to use auth() to get it working. I know it's still in alpha. Can't wait to use everything properly once it gets released
S
saM69420•364d ago
I ran into this issue with my client component and the solution was to import the server action into the parent server component and pass it down to the client component.
When using client components you need to make sure you use prop drilling to ensure that headers are available.
https://clerk.com/docs/nextjs/server-actions#with-client-components
Server Actions | Clerk
Learn how to use Clerk with Next.js Server Actions
JP
James Perkins•363d ago
Yup forgot to circle back. We release docs to explain how to use it today.
Want results from more Discord servers?
Add your server
More Posts
Testing on project with @t3-oss/env using vitestWhen I try to write unitest on brand new create-t3-app ("initVersion": "7.13.0") with vitest installT3 for a chat appAlthough I don't remember the exact video now. I remember Theo saying that the t3 stack would not beHow do I use a tRPC procedure outside a react componentHello guys, I made a simple router which will give me similar tags from my tags model from prisma `Syntax help for useQuery with no inputshi, i have two queries in my component, however on my first query I can't pass in refetchOnMount? anAlternative to Planetscale for multiple smaller appsHi While creating our latest tool, I used the tRPC + Planetscale + Clerk stack and fell in love witRemoving unused importsA rather annoying and controversial thing that was built into version 7.3.2. As far as I can see, tvariable initialized useState as true but the state is falsehasReaction is true, but liked is false error gets printed multiple times const hasReaction = poscreate-t3-turbo monorepo: How to access user session to packages/db?I would like to access some props from user's session to **prisma middleware** i.e. in below exampleCreating an update mutation with tRPCHi everyone, I'm trying to use an update mutation in this way: ```ts export const beerRouter = creatCreate and Download PDFI have a web app that allows users to edit a table including drag/dropping rows, change row colors, Is it possible to pass a zod schema as a prop?I have this ```ts interface Props { schema: ZodSchema; children: React.ReactNode; defaulLoading state of a `'use server'` componentIs it possible to have a loading state for e.g. a form submission using the new `use server` directiHow do you self host your projects in a vpswithout relying on any cpanel or vercel, i have a vps and i usually move the project using git and Geniune question: php vs server componentsI love nextjs. I hear a lot of comments about nextjs just reinvented php. Can someone clarify thingsHow do you fetch an svg from s3 into an angular app?I tried several things, but each time the svg isn't displayed.What's this errorit was working till yesterday then i added stateDistrict to address model then i started to get thisPrisma find many undefinedHello, In my other projet when i do `prisma.resource.findMany({select: ...})` the type is `{id: strESLint to force @types in dev-dependenciesWe recently had an outage coz someone installed the @types/[package-name] in dependencies, but neverUpdating existing T3 with Supabase Auth from Next AuthBackground: - Launched a T3 app with Next Auth. - Currently got 3000 users. - Launching an app vetRPC + AppRouter without reactQueryhi everyone how can i host trpc on next.js and use trpc on server components without using react que