Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NextJS Error: Your `getServerSideProps` function did not return an object

I have a reddit like application. The node/express TypeORM server with postgres db is on Heroku. The client with Next.js is on Vercel. Registration, comments, upvote/downvote are working fine. When I try to create a new community I get the following error:

502: BAD_GATEWAY Code: NO_RESPONSE_FROM_FUNCTION ID: cdg1::lrlvg-1612986052014-c0b0a2cd09ac

In Vercel function logs or on PC in terminal I get an error:

Error: Your getServerSideProps function did not return an object. Did you forget to add a return?

The code:

export const getServerSideProps: GetServerSideProps = async ({ req, res }) => {
  try {
    const cookie = req.headers.cookie
    if (!cookie) throw new Error('Missing auth token cookie')

    await Axios.get('/auth/me', { headers: { cookie } })

    return { props: {} }
  } catch (err) {
    res.writeHead(307, { Location: '/login' }).end()
  }
  
}

When I run the client and the server on PC it works, but when deployed I get the error posted above.

like image 908
Vilmos Szabó Avatar asked Oct 19 '25 04:10

Vilmos Szabó


1 Answers

From Next.js 10 getServerSideProps supports returning a redirect object for this exact purpose - which also solves the error you're getting by explicitly returning an object.

export const getServerSideProps: GetServerSideProps = async ({ req, res }) => {
    try {
        const cookie = req.headers.cookie
        
        if (!cookie) throw new Error('Missing auth token cookie')

        await Axios.get('/auth/me', { headers: { cookie } })

        return { props: {} }
    } catch (err) {
        // Handle error

        return {
            redirect: {
                destination: '/login',
                statusCode: 307
            }
        }
    }
}
like image 115
juliomalves Avatar answered Oct 21 '25 20:10

juliomalves