Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional redirection in Next.js

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?

like image 999
Yanis Urbis Avatar asked Jul 14 '17 09:07

Yanis Urbis


People also ask

How do I redirect in getInitialProps?

Solution #1: getInitialProps() To do a quick recap, getInitialProps() is a function/method that lets you write server code before the page component in Next. JS gets rendered. In that function/method you can redirect a user to an internal or external URL via the server side.

How do I redirect in getStaticProps?

You can achieve this by just switching the function getStaticProps to getServerSideProps . The entire function will execute on the server and your redirection will happen.

How do I link to another javascript page?

When linking between pages on websites, you use the <a> HTML tag. In Next. js, you can use the Link Component next/link to link between pages in your application. <Link> allows you to do client-side navigation and accepts props that give you better control over the navigation behavior.


1 Answers

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(`/`)
        }
...
like image 154
Soorena Avatar answered Oct 02 '22 17:10

Soorena