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);
this.props
is not available in the constructor.ctx.req && ctx.req.session && ctx.req.session.passport
really truthy?pageProps
ingetInitialProps
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.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.