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

Creating multiple layouts in Next.js based on your project's needs is a common practice. Let's explore

I have been working on the following starter project: https://github.com/vercel/nextjs-subscription-payments The default content provided in the above link serves as the home page for my project. Now, I am looking to create an admin and dashboard section ...

Switching over to Typescript: Sending mapped properties

I'm having trouble converting my React.JS script to TypeScript. I need assistance in creating a drop-down navigation bar on my website. Here's a snippet from my Header.tsx file: The error message Property 'onClick' does not exist on t ...

Encountering a parse error while trying to import an image in Next.js

I'm encountering an issue while trying to import an image in Next.js. Despite the image being located in the public folder, I am receiving an error when running the server. Can anyone provide assistance with this problem? Error: Failed to parse src ...

Learn the process of transmitting data from middleware to components and APIs in Next.js version 13

I've been experimenting with the Next Js 13 middleware feature and I'm a bit confused about how to pass data from the middleware to components/pages/api. For example, when trying to pass payload data or determine who the currently logged-in user ...

Upon successfully maneuvering vendors who fail to load the NEXT.JS Link

Here is an image that is not displaying properly. The navbar's responsiveness seems to be causing the issue. return ( <Link key={index} href={'/'+item.id} > <li className="nav-item dropdown position-stati ...

Using rxjs takeUntil will prevent the execution of finalize

I am implementing a countdown functionality with the following code: userClick=new Subject() resetCountdown(){this.userClick.next()} setCountDown() { let counter = 5; let tick = 1000; this.countDown = timer(0, tick) .pipe( take(cou ...

Utilizing Redux state within _app.tsx in NextJS: A comprehensive guide

This snippet of code pertains to my _app.tsx file import '../styles/globals.css' import AppNav from '../components/AppNav' import type { AppProps } from 'next/app' import { store } from '../store' import { Provider } ...

Incorporating Chakra UI, what is the best way to display a modal box upon page load?

Is there a way to display a modal box when the page loads in Chakra UI? I have been searching through Chakra's documentation but couldn't find any information on this. import { useDisclosure, Modal, ModalOverlay, ModalContent, ...

How can I target the initial last element within an *ngFor loop?

In my current project using Ionic, I am developing a personal application where I aim to implement an alphabetical header/divider for a list of games. The idea is to check the first letter of each game, and whenever it differs from the last game's ini ...

What is the best way to mention an ID for a patch request while utilizing useFormState in NextJS?

Currently in my NextJS 14 project, I am utilizing useFormState to manage a form that enables users to update their profile. The issue is with the endpoint being PATCH /user/:userId and not having a straightforward way to pass the userId to the server actio ...

Enhancing current interfaces

I'm exploring Koa and the module system in Node.js. Although I'm not asking about a specific koa question, all the code I'm working with involves using koa. In Koa, every request is defined by the Request interface: declare module "koa" { ...

Guide to configure Validator to reject the selection of the first index option in Angular 2

When using a select option, it should be set up like: <div class="form-group row" [ngClass]="{'has-error': (!form.controls['blockFirstIndex'].valid && form.controls['blockFirstIndex'].touched), 'has-success&ap ...

When selecting a different file after initially choosing one, the Javascript file upload event will return e.target as null

Currently, I have implemented file uploading using <input>. However, when attempting to change the file after already selecting one, the website crashes and states that event.target is null. <Button label="Upload S3 File"> <input ...

What advantages could learning ReactJS first give me before diving into NextJS?

Just mastered TS and now faced with the decision of choosing a framework. I'm curious why it's recommended to learn ReactJS before NextJS. I've read countless articles advising this, but no one seems to delve into the reasons behind it. Ca ...

Display embedded ng-template in Angular 6

I've got a template set up like this <ng-template #parent> <ng-template #child1> child 1 </ng-template> <ng-template #child2> child 2 </ng-template> </ng-template> Anyone know how t ...

Type inference error in TypeScript occurs within a conditional statement when the condition relies on the output of a function call rather than a boolean expression

In my TypeScript code, I have a Linked List class that is working perfectly. The class includes a Node type and functions to add items to the list. type ListItem = number | string | object; class Node { private value: ListItem; private next: Node | nu ...

Troubleshooting TypeScript in Visual Studio Code

Currently, I'm attempting to troubleshoot the TypeScript code below using Visual Studio Code: class Student { fullname : string; constructor(public firstname, public middleinitial, public lastname) { this.fullname = firstname + " " + ...

Unable to destructure props and assign them to a react-bootstrap component

I recently installed react-bootstrap and I am looking to customize the default buttons in my project. My goal is to simplify the button creation process by just using <Button> without specifying a variant option for most buttons. import * as bs from ...

Guide on specifying a type for a default export in a Node.js module

export const exampleFunc: Function = (): boolean => true; In the code snippet above, exampleFunc is of type Function. If I wish to define a default export as shown below, how can I specify it as a Function? export default (): boolean => true; ...

What is the best way to showcase text formatting applied in Strapi's WYSIWYG editor in NextJS's user interface?

I'm a beginner with Next JS and Strapi CMS. Trying to figure out how to transfer styling from the backend admin panel in Strapi to the UI in NextJS. Is there a way to display the formatted text created in Strapi's WYSIWYG editor on the frontend ...