Getting user IP in trpc without req object?

I used to get the users IP like so, just giving the package the req object:
const requestIp = require('request-ip');
const ip = requestIp.getClientIp(req);
const requestIp = require('request-ip');
const ip = requestIp.getClientIp(req);
With trpc, I don't have access to Next.JS's req object - how would I solve this now?
3 Replies
Neto
Neto2y ago
You have access On the createaContext function you have next request
plyglt
plyglt2y ago
thanks for the reply I'm not sure how exactly I would add it though Some help or a hint would help me out a lot! My context.ts file looks like this:
// src/server/router/context.ts
import * as trpc from "@trpc/server";
import * as trpcNext from "@trpc/server/adapters/next";
import { prisma } from "../db/client";

/**
* Replace this with an object if you want to pass things to createContextInner
*/
type CreateContextOptions = Record<string, never>;

/** Use this helper for:
* - testing, where we dont have to Mock Next.js' req/res
* - trpc's `createSSGHelpers` where we don't have req/res
**/
export const createContextInner = async (opts: CreateContextOptions) => {
return {
prisma,
};
};

/**
* This is the actual context you'll use in your router
* @link https://trpc.io/docs/context
**/
export const createContext = async (
opts: trpcNext.CreateNextContextOptions
) => {
return await createContextInner({});
};

type Context = trpc.inferAsyncReturnType<typeof createContext>;

export const createRouter = () => trpc.router<Context>();
// src/server/router/context.ts
import * as trpc from "@trpc/server";
import * as trpcNext from "@trpc/server/adapters/next";
import { prisma } from "../db/client";

/**
* Replace this with an object if you want to pass things to createContextInner
*/
type CreateContextOptions = Record<string, never>;

/** Use this helper for:
* - testing, where we dont have to Mock Next.js' req/res
* - trpc's `createSSGHelpers` where we don't have req/res
**/
export const createContextInner = async (opts: CreateContextOptions) => {
return {
prisma,
};
};

/**
* This is the actual context you'll use in your router
* @link https://trpc.io/docs/context
**/
export const createContext = async (
opts: trpcNext.CreateNextContextOptions
) => {
return await createContextInner({});
};

type Context = trpc.inferAsyncReturnType<typeof createContext>;

export const createRouter = () => trpc.router<Context>();
Neto
Neto2y ago
On the createContext function On the opts parameters you have both next request and response
Want results from more Discord servers?
Add your server