Skip to content

redirectTo not working, Throwing Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client #529

@qualwebs

Description

@qualwebs

🐛 Bug report

The issue with redirection inside getInitialProps method

Current Behavior

I'm using AfterJS with razzle, Using a class component, and trying to validate the authorization inside getInitialProps method as suggested in the example of afterJs GitHub readme.

Here is the code sample

class Home extends React.Component {
    static async getInitialProps({req, res, match, history, location, ...ctx}) {
        try {
            firstSection = await api.authME('TOKEN');
        }catch (error) {
            if (error.response.status === 401) {
                return { redirectTo: '/login' };
            }
            return { error };
        }
    }
}

Expected behavior

It should redirect to login page if API returns 401 status code, Instead of throwing error Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

Reproducible example

Suggested solution(s)

Additional context

Your environment

LOCAL

Software Version(s)
React ^17.0.2
After.js ^latest
Razzle ^4.2.6
Razzle Plugins
TypeScript N/A
Node 16.14.0
Browser CHROME
npm/Yarn NPM
Operating System WINDOWS

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions