How can I set a Cookie from the server (for the login)?
This code is not working..
import { initTRPC } from "@trpc/server";
import { createHTTPServer } from "@trpc/server/adapters/standalone";
import cors from "cors";
import { z } from "zod";
const t = initTRPC.create();
const publicProcedure = t.procedure;
const router = t.router;
const appRouter = router({
login: publicProcedure
.input(
z.object({
login: z.string(),
password: z.string(),
})
)
.mutation(async (opts) => {
opts.ctx.res.cookie("cokkieName", 7777, {
maxAge: 900000,
httpOnly: true,
});
}),
});
export type AppRouter = typeof appRouter;
// create server
createHTTPServer({
middleware: cors(),
router: appRouter,
createContext({ req, res }) {
return { req, res };
},
}).listen(2022);
import { initTRPC } from "@trpc/server";
import { createHTTPServer } from "@trpc/server/adapters/standalone";
import cors from "cors";
import { z } from "zod";
const t = initTRPC.create();
const publicProcedure = t.procedure;
const router = t.router;
const appRouter = router({
login: publicProcedure
.input(
z.object({
login: z.string(),
password: z.string(),
})
)
.mutation(async (opts) => {
opts.ctx.res.cookie("cokkieName", 7777, {
maxAge: 900000,
httpOnly: true,
});
}),
});
export type AppRouter = typeof appRouter;
// create server
createHTTPServer({
middleware: cors(),
router: appRouter,
createContext({ req, res }) {
return { req, res };
},
}).listen(2022);
3 Replies
Your t needs to be passed the typedef of your context
As shown here https://trpc.io/docs/server/adapters/express
Express Adapter | tRPC
Example app
// created for each request
const createContext = ({
req,
res,
}: trpcExpress.CreateExpressContextOptions) => ({}); // no context
type Context = Awaited<ReturnType<typeof createContext>>;
const t = initTRPC.context<Context>().create();
// created for each request
const createContext = ({
req,
res,
}: trpcExpress.CreateExpressContextOptions) => ({}); // no context
type Context = Awaited<ReturnType<typeof createContext>>;
const t = initTRPC.context<Context>().create();