Avoid obtaining cookies within the TRPC environment

Recently, I've been setting up TRPC with Next.js and attempting to implement server-side rendering where I fetch user data before the page loads using the trpc.useQuery hook. However, I'm facing an issue where I cannot access the JWT token cookie in the trpc context.

Here is a snippet of the code from my [username].tsx page:

const UserPage: NextPage = () => {
  const router = useRouter();
  const username = router.query.username as string;

  const user = trpc.useQuery([
    "user.by-username",
    {
      username,
    },
  ]);

  return <Text>{user?.data?.id}</Text>;
};

export default UserPage;

Additionally, here's a section of the code from the trpc context where I encounter difficulty accessing the cookies:

export const createContext = (opts?: trpcNext.CreateNextContextOptions) => {
  const req = opts?.req;
  const res = opts?.res;

  console.log(req?.cookies) // Unable to retrieve cookies at this point

  const user = jwt.verify(req?.cookies.token as string, process.env.JWT_SECRET as string) as User

  return {
    req,
    res,
    prisma,
    user
  };
};

type Context = trpc.inferAsyncReturnType<typeof createContext>;

export const createRouter = () => trpc.router<Context>();

Answer №1

Here is the answer taken from a discussion on github regarding progeny.

When dealing with server-side rendering, headers are not automatically copied over, so you will need to add the following snippet:

export default withTRPC<AppRouter>({
  // @typescript-eslint/no-unused-vars
  config({ ctx }) {
    /**
     * If you want to use SSR, you need to
     * use the server's full URL
     * @link https://trpc.io/docs/ssr
     */
    return {
      headers() {
        return {
          cookie: ctx?.req?.headers.cookie,
        };
      },
    }
  }
})

To address this issue, there is an open pull request for enhancing the documentation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Optimal method for displaying the children component twice in Next.js

In order to create an infinite slider, I had to duplicate the data within my component. The data consists of an array containing a maximum of 20 items, each with an image. The slider is functioning perfectly. Although it may seem unconventional, it was n ...

Having trouble with the Ng multiselect dropdown displaying empty options?

I'm currently facing a challenge in adding a multiselect dropdown feature to my project. Below is the code I have been working on: HTML <ng-multiselect-dropdown [settings]="searchSettings" [data]="dummyList" multiple> </n ...

Implementing Bootstrap 5 JS within an Angular 11 component TypeScript

I am currently working on a project that utilizes Angular 11 and we are aiming to integrate Bootstrap 5 native JS without relying on third-party libraries like ng-bootstrap, MDB, or ngx-bootstrap (jQuery is not being used as well). I understand that using ...

Determine the category of a container based on the enclosed function

The goal is to determine the type of a wrapper based on the wrapped function, meaning to infer the return type from the parameter type. I encountered difficulties trying to achieve this using infer: function wrap<T extends ((...args: any[]) => any) ...

A guide on setting up an HTTP proxy for API requests in Next.js

After exhausting my options online, I still haven't found a solution that works. My First Attempt (src/pages/api/proxy/[...slug].js): import { createProxyMiddleware } from 'http-proxy-middleware'; // Defining the proxy instance outside of t ...

Unpacking and reassigning variables in Vue.js 3 using TypeScript

I am working with a component that has input parameters, and I am experimenting with using destructuring assignment on the properties object to reassign variables with different names: <script setup lang="ts"> const { modelValue: isSelected ...

The 'posts' binding element is assumed to have a type of 'any' by default

Currently, I'm working on a code project that involves graphql, react, and typescript. In the middle of the process, I encountered an error message stating "Binding element 'posts' implicitly has an 'any' type." I am unsure about w ...

Sharing databases between Next.js API routes allows for efficient data management and

I am thinking about using next.js routes api as a backend service to serve database results in json format. However, I have noticed that it is not possible to keep the database up and running because all files are located at pages/api/which makes them ephe ...

The element 'mat-toolbar' is unrecognized and not known:

Encountering an issue while executing karma tests - the error message indicates that 'mat-toolbar' is not a recognized element within the application. Here are some steps to troubleshoot this problem: 1. Confirm whether 'mat-toolbar' is ...

When a new array object is added to a nested array in a React Redux reducer, the array in the store is correctly updated but the React component

I am brand new to React and redux. Currently, I have a task where I need to implement workflows with tasks inside them. While I successfully managed to add a new workflow object to the state array, I encountered a problem when trying to add a new task - it ...

Attempt the HTTP request again only for specific status codes

When developing my Angular application, I encountered a situation where I needed to make an HTTP call to a backend server. To enhance its reliability, I decided to incorporate an interceptor to implement the retry pattern. In the past, I utilized RxJS&apo ...

Ensuring Koa ctx.query is valid prior to invoking the handler function

I'm currently working on a basic route that looks like this: router.get('/twitter/tweets', async (ctx) => { const { limit, page, search } = ctx.query ctx.body = { tweets: await twitter.all(limit, page, search), } }) The issue I ...

Retrieving values from objects using Typescript

I am facing an issue while trying to retrieve a value from an object. The key I need to use belongs to another object. Screenshot 1 Screenshot 2 However, when working with Typescript, I encounter the following error message. Error in Visual Studio Is ...

Using Angular 2's ngModel directive to bind a value passed in from an

Using [(ngModel)] in my child component with a string passed from the parent via @Input() is causing some issues. Although the string is successfully passed from the parent to the child, any changes made to it within the child component do not reflect bac ...

Combining data from various API calls into one cohesive array using RXJS

My RXJS Pipeline is structured as follows: const logs: number[] = [1, 2, 3, 4]; const url = 'http://some-url-here.com'; const pipeline = from(logs).pipe( switchMap(logId => this.callEndpoint(url, logId).pipe(map(response => response. ...

Determining the typing of a function based on a specific type condition

I have created a unique type structure as shown below: type Criteria = 'Criterion A' | 'Criterion B'; type NoCriteria = 'NO CRITERIA'; type Props = { label?: string; required?: boolean; disabled?: boolean; } & ( | ...

Acquire XML documentation for overloaded functions in Typescript

Is it possible for an overloaded function in a subclass to automatically inherit the XML documentation from its base class? When hovering over myFunc I want to be able to see the documentation from the base class when I hover over myFunc, rather than ju ...

Encountering issues in d3.js following the transition to Angular 8

After upgrading my Angular 4 app to Angular 8, I encountered an issue where the application works fine in development build but breaks in production build. Upon loading the application, the following error is displayed. Uncaught TypeError: Cannot read p ...

How can you enhance a component by including additional props alongside an existing onClick function?

As a newcomer to React and TypeScript, I've created a simple component that looks like this: const CloseButton = ({ onClick }: { onClick: MouseEventHandler }) => { const classes = useStyles(); return <CloseIcon className={classes.closeButto ...

What is the reason for user.id being set as a 'string' by default?

Currently, I am in the process of creating a Next Auth system using TypeScript, and I have encountered a type issue related to the 'user.id' data. This error is specifically happening in the callbacks section. The types of 'user.id' ar ...