Redirect inside a getInitialProps with next.js and Parse Server

EDIT :

I set a cookie when the user is connected et store the token inside a cookie. And with the GetInitialPropsi access to the cookie and i check if the session is set to an user or not.

It seems it only work when i access to this page when i use a link : home page to this page for exemple but when i type the url it doesn't work.

I'm using npm install --save next-cookies for retrieve the cookie : https://www.npmjs.com/package/next-cookies

I'm sorry it's probably a stupid question but i'm still learning ...

Here is the whole code of my page Login.js


import React, { Component, useState } from 'react'
import Parse from 'parse'
import Snackbar from '@material-ui/core/Snackbar';
import Cookies from 'js-cookie'
import cookies from 'next-cookies'

export default function login() {

    const [state, setState] = React.useState({
        username: "",
        password: "",
    }
    )

    const [error, setError] = useState(false)

    async function handleConnection() {
        try {
            const user = await Parse.User.logIn(state.username, state.password)
            console.log(user)

            var currentUser = Parse.User.current();
            const token = currentUser.getSessionToken()
            //console.log(token)
            Cookies.set('token', token, { expires: 365 })
            setError(false)
        } catch (e) {
            setError(true)
        }
    }
    function handleChange(evt) {
        const value = evt.target.value;
        setState({
            ...state,
            [evt.target.name]: value
        });
    }

    return (
        <div className="notConnected container-fluid">
            <div className="containerFormLogin">
                <h1>Connectez-vous !</h1>
                <p>{error ? "Nom d'utilisateur ou mot de passe incorrect" : ''}</p>
                <label>Nom d'utilisateur ou mail</label>
                <input type="text" name="username" onChange={handleChange} />
                <label>Mot de passe</label>
                <input type="password" name="password" onChange={handleChange} />
                <button className="pulse" onClick={handleConnection}>Se connecter</button>
                <p>Pas encore de compte ? Inscrivez-vous par ici !</p>
                <Snackbar
                    anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
                    open={error}
                    autoHideDuration={3000}
                    message={<span id="message-id">Impossible de se connecter, vérifier vos informations de connexion</span>}
                    ContentProps={{
                        "aria-describedby": "message-id"
                    }}
                ></Snackbar>
            </div>
            <style jsx>{`

                .notConnected
                {
                    background-image: url('/images/notConnected.svg');
                    height: 100vh;
                    width: 100%;
                    background-position: center;
                    background-size: cover;
                    background-repeat: no-repeat;
                    display: flex,
                }
                p:empty
                {
                    margin:0 !important;
                }
                .containerFormLogin
                {
                    width: 400px;
                    background-color: rgba(255,255,255, 0.8);
                    box-shadow: rgba(0,0,0, 0.5) 10px 10px 10px;
                    border-radius: 10px;
                    display: flex;
                    flex-direction: column;
                    padding: 30px;
                    margin:auto;
                    transition: all .2s ease-in;
                }
                .containerFormLogin:hover
                {
                    background-color: rgba(255,255,255, 1);
                }
                .containerFormLogin h1
                {
                    margin-bottom: 40px;
                    font-family: 'Raleway', sans-serif;
                    font-size: 25px;
                    text-align: center;
                }
                .containerFormLogin p
                {
                    font-size: 12px;
                    font-family: 'Raleway', sans-serif;
                    margin-top: 10px;
                }
                .containerFormLogin label
                {
                    font-size: 12px;
                    font-family: 'Raleway', sans-serif;
                }
                .containerFormLogin input
                {
                    margin-bottom: 20px;
                    font-family: 'Raleway', sans-serif;
                    font-size: 15px;
                    padding-top: 10px;
                    padding-bottom: 10px;

                }
                .error
                {
                    border-color: red;
                }
                button 
                {
                background: none;
                border: 2px solid;
                font: inherit;
                line-height: 1;
                padding: 1em 2em;
                color:  #ef6eae;
                -webkit-transition: 0.25s;
                transition: 0.25s;
                }
                button:hover, button:focus {
                border-color: #ef8f6e;
                color: #ef8f6e;
                }
                .pulse:hover,
                .pulse:focus {
                -webkit-animation: pulse 1s;
                        animation: pulse 1s;
                box-shadow: 0 0 0 2em rgba(255, 255, 255, 0);
                }

                @-webkit-keyframes pulse {
                0% {
                    box-shadow: 0 0 0 0 #ef8f6e;
                }
                }

                @keyframes pulse {
                0% {
                    box-shadow: 0 0 0 0 #ef8f6e;
                }
                }

            `}</style>
        </div >
    )
}

login.getInitialProps = (ctx) => {

    const allCookies = cookies(ctx).token;

    const UserToken = Parse.User.me(allCookies)
    if (UserToken) {
        // the user is connected so we do the redirection beacause when he's connected he can't have access to this page
        return (
            UserToken
        )
    } else {
        // Do something else

    }


}

EDIT #2 :

When i reach the page with a link like homePage to the login page i have this error

Unhandled Rejection (TypeError): res is undefined

and when I'm reloading the page or if i access by his url he give me an other error :

ReferenceError: localStorage is not defined

Here is my getInitialProps:

connexion.getInitialProps = ({ ctx, res }) => {

    const cookies = Cookies.get('tokenUserParse');

    const UserToken = Parse.User.me(cookies)
    if (UserToken) {
        // the user is connected so we do the redirection beacause when he's connected he can't have access to this page

        res.writeHead(403, {
            Location: '/'
        });
        res.end();

    } else {
        // Do something else

    }
}

Upvotes: 0

Views: 1383

Answers (1)

Davi Mac&#234;do
Davi Mac&#234;do

Reputation: 2984

You need to understand that the same code that you have in getInitialProps will run both in the server (Node.js environment) and in the browser (javascript). Some libraries will work well for both environments but some libraries won't. So sometimes you need to perform different actions depending on which environment the code is running in. Something like this should fix your problem:

const isServer = typeof window === 'undefined';

const Parse = isServer ? require('parse/node') : require('parse');

connexion.getInitialProps = async ({ ctx, res }) => {

    const cookies = Cookies.get('tokenUserParse');

    const UserToken = await Parse.User.me(cookies)
    if (UserToken) {
        // the user is connected so we do the redirection beacause when he's connected he can't have access to this page

        if (isServer) {
            res.writeHead(302, {
                Location: '/'
            });
            res.end();
        } else {
            document.location.href = '/'
        }
    } else {
        // Do something else

    }
}

Upvotes: 0

Related Questions