Ammar Pasha
TTCTheo's Typesafe Cult
•Created by Ammar Pasha on 5/28/2023 in #questions
tRPC API calls log user out automatically
Whenever I call a tRPC API route (protected or public), I immediately get logged out. I have no idea what I'm doing wrong. Here's my code:
// [...nextauth].ts
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);
// [...nextauth].ts
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);
// post.ts (in server/api/routers)
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;
}),
});
// post.ts (in server/api/routers)
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;
}),
});
// NewPost.tsx (in components)
const createPost = api.post.create.useMutation({
onSuccess: (newPost) => {
setInputValue("");
},
});
function handleSubmit(e: FormEvent) {
e.preventDefault();
createPost.mutate({ content: inputValue });
}
// NewPost.tsx (in components)
const createPost = api.post.create.useMutation({
onSuccess: (newPost) => {
setInputValue("");
},
});
function handleSubmit(e: FormEvent) {
e.preventDefault();
createPost.mutate({ content: inputValue });
}
10 replies