2

I am using passportjs middleware for authentication and it works, but when I'm trying to use the user object in components the property is undefined, although is passed in _app.js.

The app is nextjs based with an express server. I know the user is authenticated because I can trace it in the server, but not in any component.

// _app.js
import React from 'react';
import App, { Container } from 'next/app';
import { ThemeProvider } from '@material-ui/styles';
import theme from '../theme/theme';

class MyApp extends App {
    static async getInitialProps({ Component, ctx }) {
        let pageProps = {};
        if (Component.getInitialProps) {
            pageProps = await Component.getInitialProps(ctx);
        }
        if (ctx.req && ctx.req.session && ctx.req.session.passport) {
            pageProps.user = ctx.req.session.passport.user;
        }
        return { pageProps };
    }

    constructor(props) {
        super(props);
        this.state = {
            user: props.pageProps.user
        };
    }

    render() {
        const { Component, pageProps } = this.props;

        const props = {
            ...pageProps,
            user: this.state.user,
        };

        return (
            <Container>
                <ThemeProvider theme={theme}>
                    <Component {...props} />
                </ThemeProvider>
            </Container>
        );
    }
}

export default MyApp;

Webstorm is pointing at user: this.state.user line, complaining unresolved variable user but I do not understand why is not resolved as a variable, it is defined in the constructor.

Edit: and this is the server.js

const express = require("express");
const http = require("http");
const next = require("next");
const session = require("express-session");
const passport = require("passport");
const uid = require('uid-safe');
const authRoutes = require("./auth-routes");
const oAuth2Strategy = require("./lib/passport-oauth2-userinfo");

const dev = process.env.NODE_ENV !== "production";
const app = next({
    dev,
});
const handle = app.getRequestHandler();

app.prepare().then(() => {
    const server = express();

    const sessionConfig = {
        secret: uid.sync(18),
        cookie: {
            maxAge: 86400 * 1000 // 24 hours in milliseconds
        },
        resave: false,
        saveUninitialized: true
    };
    server.use(session(sessionConfig));

    passport.use(new oAuth2Strategy(
        {
            authorizationURL: process.env.REACT_APP_AUTH_URL,
            tokenURL: process.env.REACT_APP_AUTH_TOKEN,
            clientID: process.env.REACT_APP_CLIENT_ID,
            clientSecret: process.env.REACT_APP_SECRET,
            callbackURL: process.env.REACT_APP_CALLBACK,
            userProfileURL: process.env.REACT_APP_OPENID
        },
        function(accessToken, refreshToken, extraParams, profile, done) {
            console.log(profile);
            return done(null, profile);
        }

    ));
    passport.serializeUser((user, done) => done(null, user));
    passport.deserializeUser((user, done) => done(null, user));

    server.use(passport.initialize());
    server.use(passport.session());
    server.use(authRoutes);

    const restrictAccess = (req, res, next) => {
        if (!req.isAuthenticated()) return res.redirect("/login");
        next();
    };

    server.use("/", restrictAccess);
    server.use("/profile", restrictAccess);

    server.get("*", handle);

    http.createServer(server).listen(process.env.PORT, () => {
        console.log(`listening on port ${process.env.PORT}`);
    });
});

Edit 2: thanks to @SimplyComplexable I troubleshooted a little bit. In my index.js I can access the user prop like this e.g. this.props.user.displayName with no problem.

This works:

import Landing from "./Landing"
import React from "react";

class Home extends React.Component {

    render() {
        return (
            <div>
                {this.props.user.displayName}
                <Landing />
            </div>
        )
    }
}

export default Home;

But, for example, in Landing component the prop.user is undefined. Maybe I am not accessing correctly or passing the prop somehow?

class Landing extends React.Component {
    const {user} = this.props;
    return (
        <div>
            ...
    )
}
export default withStyles(useStyles)(Landing);
12
  • Try with "this.props.pageProps.user"
    – Iiskaandar
    Commented Jul 31, 2019 at 15:16
  • @liskaandar this.props is not available in the constructor. Commented Jul 31, 2019 at 15:18
  • 1
    is ctx.req && ctx.req.session && ctx.req.session.passport really truthy? Commented Jul 31, 2019 at 15:20
  • 1
    Can you console log pageProps in getInitialProps and check if the value is actually being set? I suspect what @EmileBergeron is wondering, which is that if statement is evaluating to true so it's never being set. Commented Jul 31, 2019 at 15:52
  • 1
    Is Landing a page? I updated the code sandbox to show how you would get the prop in a page vs a component. Look at the about page and then the Landing component which is used in the index page. Commented Jul 31, 2019 at 19:06

1 Answer 1

2

The issue based on the code you have now, is that you're not passing user down to the Landing component. If you update your home page with the following changes, you're code should work.

import Landing from "./Landing"
import React from "react";

class Home extends React.Component {

    render() {
        return (
            <div>
                {this.props.user.displayName}
                <Landing user={this.props.user}/>
            </div>
        )
    }
}

export default Home;

With user specifically this would be a great opportunity for context, so that you don't have to explicitly pass down the user prop to every component. Here's a quick example:

import Landing from "./Landing"
import React from "react";

export const UserContext = React.createContext({});

class Home extends React.Component {

    render() {
        return (
            <div>
                {this.props.user.displayName}
                <UserContext.Provider value={this.props.user}>
                  <Landing user={this.props.user}/>
                </UserContext.Provider>
            </div>
        )
    }
}

export default Home;
import React from 'react';
import UserContext from './Home';

const Landing = () => {
    const user = React.useContext(UserContext);
    return (
      <div>
        {user.displayName}
      </div>
    )
}
export default withStyles(useStyles)(Landing);

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.