#Having trouble to setup auth in express and nextjs.

17 messages · Page 1 of 1 (latest)

earnest oriole
#

I have a seprate backend and frontend. Frontend in in next and backend is in express. I am trying to setup auth like this.

const session = require('express-session');
const cookieParser = require('cookie-parser');
// Middleware
require('dotenv').config();
app.use(morgan('tiny'));
app.use(bodyParser.json());
app.use(cors());
app.use(
  session({
    secret: process.env.SECRET,
    resave: false,
    saveUninitialized: false,
    cookie: { maxAge: 24 * 60 * 60 * 1000 }, // 24 hours
  })
);
app.use(cookieParser());

I am checking auth with a middleware which looks like this :

// Checks logged in or not
module.exports.isLoggedIn = (req, res, next) => {
  if (req.session.userId) {
    next();
  } else {
    res.status(401).json({ message: "Unauthorized" });
  }
};

In React I am using axios to login

  const handleSubmit = async (event) => {
    event.preventDefault();
    // Perform form submission or further processing with formData
    try {
      const response = await axios.post(
        'http://localhost:5000/auth/login',
        formData
      );
      console.log(response.data);
      setFormData({
        email: '',
        password: '',
      });
    } catch (e) {
      console.log(e);
    }
  };

The login is being executed successfully. But session is not being stored. When I try to fetch resources after login it is throwing me 401.

manic crypt
#

also you dont show how you perform the log in.

steel bramble
#

Just because next has SSR doesn't mean it's a backend

#

Sure, you can use it as a really poor replacement for one. Doesn't make it the only way to do it.

manic crypt
steel bramble
#

I know. Those are not a replacement for an API

#

For the simple reason that it doesn't scale cleanly

#

They are a good tool for API gateways and to streamline API consumption in your SSR apps but that's all they're there for

manic crypt
steel bramble
#

What? That's absurd.

manic crypt
steel bramble
#

For the reasons I just said among many other: next offers a lot more than react, even beyond SSR

earnest oriole
#

I just wanted to have seprate backend. BTW i switched to jwt. Now its fine.