DEV Community

Discussion on: Easy user authentication with Next.js

Collapse
 
chrsgrrtt profile image
Chris Garrett • Edited

It's quite common to return a 404 on protected endpoints for an unauthed user - it makes it harder to "profile" an application from the outside. Github do this, for instance. Feel free to implement differently though, for instance redirecting to the sign in screen - it's just a demo afterall...

I'm using res.statusCode, res.send inside getServerSidePros without issue; are you basing your assumption on a statically compiled next app?

Collapse
 
samuelgoldenbaum profile image
Samuel Goldenbaum

Thanks for the reply Chris.

There is an RFC for this issue. Take a look at the codesandbox demo and you will see

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

Maybe this is handled somehow in next-iron-session

Thread Thread
 
chrsgrrtt profile image
Chris Garrett

Thanks Samuel - that is very bizarre! I'm using this exact code successfully in a project at the moment, but you're right - it is an issue in the codesandbox demo... I'll do some digging.

Thread Thread
 
samuelgoldenbaum profile image
Samuel Goldenbaum

It seems to be an RFC at the moment and would be a great solution to be able to set headers - which could allow a redirect in getServerSidePros which would be great.

Currently, I have to use getInitialProps in a HOC and check if we SSR/client and do something like:

getInitialProps = async (ctx) => {
        const {token} = nextCookie(ctx);

        if (!token) {
            if (typeof window === 'undefined') {
                ctx.res.writeHead(302, {Location: '/login'});
                ctx.res.end();
            } else {
                Router.push('/login');
            }
        }

        return {};
    }
Enter fullscreen mode Exit fullscreen mode