I'm trying to build a social media application using the T3 stack (Next.js, NextAuth.js, tRPC, Prisma). I have a protectedProcedure
route which creates a new post. However, whenever I call this route (or any other route), I get immediately logged out, and since it's a protected procedure, I get an unauthorized error.
Here's my route file (named post.ts
):
import { z } from "zod";
import { createTRPCRouter, protectedProcedure } from "~/server/api/trpc";
export const postRouter = createTRPCRouter({
create: protectedProcedure
.input(z.object({ content: z.string() }))
.mutation(async ({ input: { content }, ctx }) => {
const post = await ctx.prisma.post.create({
data: {
content,
userId: ctx.session.user.id,
},
});
return post;
}),
});
Here's my [...nextauth].ts
file:
import NextAuth from "next-auth";
import { NextAuthOptions } from "next-auth";
import GoogleProvider from "next-auth/providers/google";
export const authOptions: NextAuthOptions = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
}),
],
secret: process.env.NEXTAUTH_SECRET!,
};
export default NextAuth(authOptions);
And finally, here's the part in my component file that calls the API:
const createPost = api.post.create.useMutation({
onSuccess: (newPost) => {
setInputValue("");
},
});
function handleSubmit(e: FormEvent) {
e.preventDefault();
createPost.mutate({ content: inputValue });
}