Get IP Address in tRPC router

Hey guys how can I get the IP address inside a procedure? Like this code f.ex:
export const contactRouter = createTRPCRouter({
hello: publicProcedure
.input(contactSchema)
.mutation(async ({ input, ctx }) => {
// get ip here
const msg = await db.contactMessage.create({
data: {
name: input.name,
email: input.email,
subject: input.subject,
message: input.message,
},
});
return { success: true, msg };
}),
});
export const contactRouter = createTRPCRouter({
hello: publicProcedure
.input(contactSchema)
.mutation(async ({ input, ctx }) => {
// get ip here
const msg = await db.contactMessage.create({
data: {
name: input.name,
email: input.email,
subject: input.subject,
message: input.message,
},
});
return { success: true, msg };
}),
});
8 Replies
Max
Max13mo ago
not 100% but think you can do
export async function createContext(opts: FetchCreateContextFnOptions) {
const { userId } = auth();
const ip = opts.req.headers['x-forwarded-for']
// now we can return the context
// (this will be passed to every procedure)
// so we can access the database and additionally the current user ID
return {
prisma,
clerkUserId: userId,
};
}
export async function createContext(opts: FetchCreateContextFnOptions) {
const { userId } = auth();
const ip = opts.req.headers['x-forwarded-for']
// now we can return the context
// (this will be passed to every procedure)
// so we can access the database and additionally the current user ID
return {
prisma,
clerkUserId: userId,
};
}
and then on the request object you may be able to grab
req.headers['x-forwarded-for']
req.headers['x-forwarded-for']
or
req.ip
req.connection.remoteAddress
req.ip
req.connection.remoteAddress
and pass that to your context? @sommeeer
sommeeeR
sommeeeR13mo ago
im not using any user tho its a public procedure
Max
Max13mo ago
i meant
const ip = opts.req.headers['x-forwarded-for']
const ip = opts.req.headers['x-forwarded-for']
and pass the ip to ctx not 100% sure on this, but might be possible this way.
sommeeeR
sommeeeR13mo ago
ok
Max
Max13mo ago
@sommeeer did that help or nah?
sommeeeR
sommeeeR13mo ago
Didnt figure it out :/
Max
Max13mo ago
dang keep at it im sure you can brute force the solution eventually. Thats how i do things
K1|ller
K1|ller13mo ago
this worked for me const clientIP = req.headers['x-forwarded-for'] || req.socket.remoteAddress; I did that in express, I haven't tried it in trpc
Want results from more Discord servers?
Add your server