The type 'GetServerSidePropsContext<ParsedUrlQuery, PreviewData>' does not include property X

My current setup includes:

type Session = {
  bearer: string,
  firstName: string,
  lastName: string,
  etc...
};

interface ServerContext extends GetServerSidePropsContext {
    session: Session,
};

export type ServerProps<P extends { [key: string]: any } = { [key: string]: any }> = (
    context: ServerContext
) => Promise<GetServerSidePropsResult<P>>;

export const requireAuth = (gssp: GetServerSideProps) => {
  return async (ctx: GetServerSidePropsContext) => {
    const { req } = ctx;
    const session = req?.headers?.cookie ? await getSession(req?.headers?.cookie) : null;

    if (!session) {
      return {
        redirect: { permanent: false, destination: '/login' }
      };
    };

    const serverSession = { ...ctx, session };

    return await gssp(serverSession);
  };
};

When using it, I follow this pattern:

export const getServerSideProps: ServerProps = requireAuth(async _ctx => {
  const { session } = _ctx;

  let account = session;
  let stats = {};

  try {
    stats = fetchSomeData
  } catch (error) {
    console.log('Pages/Index Fetching Error: ', error);
  }

  return {
    props: {
      account: account,
      stats: stats,
      navbar: true,
      footer: true,
    },
  };
});

The problem arises when accessing 'session' in '_ctx', triggering the error message: "Property session does not exist on type 'GetServerSidePropsContext<ParsedUrlQuery, PreviewData>'"

To bypass this issue, modifying 'index.d.tsx' within 'next/types' by adding 'session: Session' to GetServerSidePropsContext works, but extending the interface as shown above fails to resolve the problem.

Answer №1

const checkAuthentication = (gssp: ServerProps) => {
  return async (ctx: GetServerSidePropsContext) => {
    const { req } = ctx;
    const session = req?.headers?.cookie ? await getSession(req?.headers?.cookie) : null;

    if (!session) {
      return {
        redirect: { permanent: false, destination: '/login' }
      };
    };

    const serverSessionData = { ...ctx, session };

    return await gssp(serverSessionData);
  };
};

It would be better to use ServerProps instead of GetServerSideProps

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

What is the best way to implement conditional rendering for the next/image component in a React project?

I am facing a challenge with my library that is being utilized across various websites. One of these websites is built on Next JS, and I am looking to implement the next/image component for all images on this particular site without impacting the functio ...

In React-Typescript, the second index of the todos array is constantly being updated while the rest of the array remains unchanged

I am struggling to get my Todo-List working with typescript-react. The code I have doesn't seem to be functioning properly. Here is a snippet of my App.tsx: import { useState } from "react"; import "./App.css"; export default fun ...

Executing NextJS Request on Each Route Transition

I am working on a project with NEXTJS 13 and a Pages directory. I am looking to make a request to our graphql server every time a route changes. Is it possible to do this from the server-side? Additionally, can I store this data in my Redux store after m ...

Best practices for annotating component props that can receive either a Component or a string representing an HTML tag

What is the correct way to annotate component props that can accept either a Component or a string representing an HTML tag? For instance, imagine I have a component that can receive a custom Component (which includes HTML tags like div, p, etc.). The cod ...

Is there a syntax available for type annotation of arrays created from pre-declared variables?

According to my standards, all possible annotations are required in TypeScript. Therefore, TypeScript-ESLint is prompting me to annotate the `[ responseData, cognitoUser ]`. However, when I try to use the syntax `[ responseData1: ResponseData1, responseD ...

Choosing the primary camera on a web application with multiple rear cameras using WebRTC

Having a bit of trouble developing a web app that can capture images from the browser's back camera. The challenge lies in identifying which camera is the main one in a multi-camera setup. The issue we're running into is that each manufacturer u ...

How can one click the button within the expanded dropdown while hovering over the navigation item in Angular and Bootstrap?

Issue Description: Upon hovering over a navigation item, the dropdown container is displayed but it's not clickable. Desired Behavior: Hovering over a navigation item should display the dropdown container and allow clicking on its contents. Furthermo ...

I'm having some trouble with my middleware test in Jest - what could be going wrong?

Below is the middleware function that needs testing: export default function validateReqBodyMiddleware(req: Request, res: Response, next: NextFunction) { const { name, email }: RequestBody = req.body; let errors: iError[] = []; if (!validator.isEmai ...

The error message indicates a compatibility issue between parameters 'r' and 'a'

Attempting to reproduce the code found in this blog post, but encountering some perplexing errors. import { option, identity, apply } from 'fp-ts'; import type { Kind, URIS } from 'fp-ts/HKT'; import { pipe } from 'fp-ts/lib/functi ...

struggling to maintain image centering when window is resized in next.js

Struggling with keeping my Next.js Image component centered when resizing the window. I've attempted using margin auto, display flex with justify-content and align content centered, as well as object-fit and object position properties. Tried various ...

Flex-Layout in Angular - The Ultimate Combination

Recently, I decided to delve into Angular and the Flex-Layout framework. After installing flex-layout through npm, I proceeded to import it in my app.module.ts file like so: import { FlexLayoutModule } from '@angular/flex-layout'; imports: [ Fl ...

Issue encountered with Tailwind and Next.js: Backslash missing before semicolon

This issue has been giving me a headache for quite some time. Everything was running smoothly, and then out of nowhere, it stopped compiling. Upon running npm run dev, I encountered the following error: Error - ./node_modules/next/dist/build/webpack/loa ...

ESlint is unable to parse typescript in .vue files

After using vue ui to build my project, here is the content of my package.json: "@vue/cli-plugin-eslint": "^4.1.0", "@vue/cli-plugin-typescript": "^4.1.0", "@vue/eslint-config-standard": "^4.0.0", "@vue/eslint-config-typescript": "^4.0.0", "eslint": "^5.1 ...

Encountering issues while deploying Heroku with React and Next.js

After successfully running my react/next js app with no errors or warnings on my localhost, I encountered deployment issues on Heroku. Each time I try to deploy, I consistently receive an error indicating that the posts array (in pages/landing.js) is undef ...

What is the best way to bring a local package into another npm package and verify its functionality using Typescript?

In a scenario where there are 3 npm projects utilizing Webpack and Typescript, the folder structure looks like this: ├── project1/ │ ├── tsconfig.json │ ├── package.json │ ├── src/ │ │ └── index.ts │ ...

Troubleshooting Problem with Next.js 13 Integration, Supabase, and Server Actions in layout.tsx

I'm currently developing a Next.js 13 application and experimenting with managing user authentication through Supabase. I've encountered some challenges when attempting to verify if a user is logged in using an asynchronous function within my lay ...

Issue: Button ClickEvent is not triggered when the textArea is in onFocus mode

Is there a way to automatically activate a button ClickEvent when the textArea input is focused? Keep in mind that my textArea has some styles applied, causing it to expand when clicked. Here is an example: https://stackblitz.com/edit/angular-ivy-zy9sqj?f ...

Using an iPhone client and node.js server for authentication through Facebook and Twitter

Forgive me for asking such a broad question, but this is my first attempt at creating the server backend for an iPhone app. The scenario is quite basic: when users open the iPhone app for the first time, they will encounter a login screen where they can c ...

TS: A shared function for objects sharing a consistent structure but with varied potential values for a specific property

In our application, we have implemented an app that consists of multiple resources such as Product, Cart, and Whatever. Each resource allows users to create activities through endpoints that have the same structure regardless of the specific resource being ...

"Capture the selected option from a dropdown menu and display it on the console: A step-by-step

Is there a way to store the selected value from a dropdown in a variable and then display it on the console? HTML <select class="form-control box" id="title" required> <option *ngIf="nationality_flag">{{nationality}}</option> &l ...