13

Is it possible to conditionally redirect a user to another Url based on cookie value? I know I can inspect cookie on a server & then redirect. But what should I do if a user came through Link. (I can't use Route.push because it's undefined on the server) Is there any way to use Router only on the browser?

I know at least one way to do this: to create simple button and add Router push & check cookies inside onClick handler, but is it a correct way to do this?

1 Answer 1

24

you can check if user has accessed the page via server or client side. and after that you can conditionally redirect with the proper tool. getInitialProps function gets a ctx object. you can check whether its on server or client like this:

import Router from 'next/router'

export default class Browse extends Component {

    static async getInitialProps (ctx) {
        if (ctx && ctx.req) {
            console.log('server side')
            ctx.res.writeHead(302, {Location: `/`})
            ctx.res.end()
        } else {
            console.log('client side')
            Router.push(`/`)
        }
...
Sign up to request clarification or add additional context in comments.

1 Comment

Avoid 301 unless you're really sure. Use 302 for temporary moves.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.