3

I have my express server on a different port than my client-side nextjs project.

I know when you have a server on the same port you can use getRequestHandler with next that passes the user object to be accessible with getInitialProps in the client-side.

const express = require("express");
const next = require("next");

const app = next({ dev: true });
const handle = app.getRequestHandler();

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

  // adds passport session
  require("./middlewares").init(server);

  const apolloServer = require("./graphql").createApolloServer();
  apolloServer.applyMiddleware({ app: server });

  server.all("*", (req, res) => {
    return handle(req, res);
  });

  server.listen(port, (err) => {
    if (err) throw err;
  });
});

My passport implementation is as follows

const config = require("../config");
const session = require("express-session");
const passport = require("passport");

exports.init = (server, db) => {
  require("./passport").init(passport);

  const sess = {
    name: "pid",
    secret: config.SESSION_SECRET,
    cookie: { maxAge: 2 * 60 * 60 * 1000 },
    resave: false,
    saveUninitialized: false,
    store: db.initSessionStore(),
  };

  if (process.env.NODE_ENV === "production") {
    server.set("trust proxy", 1);
    sess.cookie.secure = true;
    sess.cookie.httpOnly = true;
    sess.cookie.sameSite = 'none';
    sess.cookie.domain = process.env.DOMAIN;
  }

  server.use(session(sess));
  server.use(passport.initialize());
  server.use(passport.session());
};

And running the following on the express server, I can see req.user returning the user object.

app.use((req, res, next) => {
  console.log(req.user);
  next();
});

In a page in my nextjs app, in getInitialProps req.user is undefined

Home.getInitialProps = async (ctx) => {
  const { req } = ctx;
  const { user } = req;
  console.log(user);
  ..........
};

Is there a way to either access the passport user object via SSR in nextjs or a different method to authorize and user on a page?

I do have a Github Repo with instructions on how to run the app in the README.md

mcclosa
  • 943
  • 7
  • 29
  • 59
  • I just downloaded your github repo and played around a bit. There are some issues for people trying to reproduce your problem. There seems to be a minimum of 6 characters needed for the fake data username, but you supply *admin* which only has 5. Another problem is that apollo bitches, because it receives no absolute base url, because the *.env* file where it is specified is missing from the client. I tried to use `getServerSideProps` instead of `getInitialProps` in your project, but it seems like you defined `getInitialProps` somewhere extra where I am not aware of. – Gh05d Jul 19 '21 at 12:25

1 Answers1

0

Passport auth doesn't seems work across port. The solution is put a ngnix in front. Local passport authorization on different ports

LarryX
  • 591
  • 2
  • 7