question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

InferGetServerSidePropsType doesn't work with conditional returns

See original GitHub issue

Verify canary release

  • I verified that the issue exists in Next.js canary release

Provide environment information

❯ next info

Operating System:
  Platform: darwin
  Arch: x64
  Version: Darwin Kernel Version 20.6.0: Tue Feb 22 21:10:41 PST 2022; root:xnu-7195.141.26~1/RELEASE_X86_64
Binaries:
  Node: 17.9.0
  npm: 8.5.5
  Yarn: N/A
  pnpm: N/A
Relevant packages:
  next: 12.1.6-canary.16
  react: 18.0.0
  react-dom: 18.0.0

What browser are you using? (if relevant)

No response

How are you deploying your application? (if relevant)

No response

Describe the Bug

In the documentation here: https://nextjs.org/docs/api-reference/data-fetching/get-server-side-props#redirect

We are shown that we can return a redirect or a notFound instead of props. I have attempted to do that in TypeScript here:

export default function user({ user }: InferGetServerSidePropsType<typeof getServerSideProps>) {
    return (
        <div>{user}</div>
    );
}

export const getServerSideProps = async ({ req }: GetServerSidePropsContext) => {
    const userJwt = parseCookies({ req })['jwt']
    if (!userJwt) {
        return { redirect: { destination: '/login', permanent: false } }
    }

    const user = await prisma.users.findFirst()
    return { props: { user } }
}

If there is logic handling a conditional redirect, we don’t get type inference. Here is a WebStorm screenshot showing that: image

Once I remove the conditional logic:

export default function user({ user }: InferGetServerSidePropsType<typeof getServerSideProps>) {
    return (
        <div>{user?.email}</div>
    );
}

export const getServerSideProps = async ({ req }: GetServerSidePropsContext) => {
    const user = await prisma.users.findFirst()
    return { props: { user } }
}

Then type inference works again: image

Expected Behavior

Type inference works with conditionals.

To Reproduce

One way of reproducing is copy/pasting what I provided in the bug description:

export default function user({ user }: InferGetServerSidePropsType<typeof getServerSideProps>) {
    return (
        <div>{user}</div>
    );
}

export const getServerSideProps = async ({ req }: GetServerSidePropsContext) => {
    const userJwt = parseCookies({ req })['jwt']
    if (!userJwt) {
        return { redirect: { destination: '/login', permanent: false } }
    }

    const user = await prisma.users.findFirst()
    return { props: { user } }
}

This however requires extra dependencies to be installed. With no dependencies, you can simply take the example from the docs and attempt to use type inference with it: https://nextjs.org/docs/api-reference/data-fetching/get-server-side-props#redirect

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:11

github_iconTop GitHub Comments

4reactions
anthonyalayocommented, May 3, 2022

That worked, thank you @GabenGar! Here it is completely, so people can reference it in the future:

import { prisma } from '../db'
import { users } from '@prisma/client'
import { GetServerSideProps, InferGetServerSidePropsType } from "next/types";
import { parseCookies } from "nookies";

export default function Users({ users }: InferGetServerSidePropsType<typeof getServerSideProps>) {
    return (
        <ul>
            {users.map(user => (
                <li key={user.id}>{user.email}</li>
            ))}
        </ul>
    );
}

interface IProps {
    users: users[]
}

export const getServerSideProps: GetServerSideProps<IProps> = async ({ req }) => {
    const userJwt = parseCookies({ req })['jwt']
    if (!userJwt) {
        return { redirect: { destination: '/login', permanent: false } }
    }

    const users = await prisma.users.findMany()
    return { props: { users } }
}

My mistake was that I did this:

interface IProps {
    props: {
        users: users[]
    }
}

@GabenGar, aren’t we returning an object with everything inside a props object? Why does including that in the interface not work? I’m confused about that.

2reactions
anthonyalayocommented, May 3, 2022

Thanks @GabenGar, that makes sense. I appreciate the help!

@balazsorban44, could this ticket track making the documentation here more clear? https://nextjs.org/docs/api-reference/data-fetching/get-server-side-props#getserversideprops-with-typescript

I’m not a TypeScript expert, but I could imagine others getting confused by it as well.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Place getServerSideProps function in an helper - Stack Overflow
I am getting errors when deploying to Vercel. Can anyone help me with the my issues below? 0 · Conditional getServerSideProps · Hot...
Read more >
Data Fetching: getServerSideProps - Next.js
API reference for `getServerSideProps`. Learn how to fetch data on each request with Next.js.
Read more >
The Confusing Core Of NextJS - getServerSideProps - YouTube
I hate NextJS. It's awesome.Seriously tho getServerSideProps is a...rough pattern, and I hope this helps clarify why I think soALL MY ...
Read more >
Conditional data rendering based on authentication - YouTube
Creating the UI using Next.js: Conditional data rendering based on authenticationIn this course, we take a quick look at Strapi v4 and ...
Read more >
How To Automatically Get Props Types in Next.js and TypeScript
Whenever this logic is used, InferGetServerSidePropsType and InferGetStaticPropsType fail and return never as props type. In other words, this ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found