Advanced Node and Express - Implement the Serialization of a Passport User

Tell us what’s happening:

I’m struggling to connect my database. I’ve copied the server.js exactly as the instructions said but It’s not working. I assume it might be that I’ve did something wrong with the url but I don’t know and I’ve been trying to look at all the tutorials online but they seem different and saying different things. It is important to note that I’m using Replit to do this.

My code so far: server.js

‘use strict’;
require(‘dotenv’).config();
const express = require(‘express’);
const myDB = require(‘./connection’);
const fccTesting = require(‘./freeCodeCamp/fcctesting.js’);
const session = require(‘express-session’);
const passport = require(‘passport’);
const { ObjectID } = require(‘mongodb’);

const app = express();

app.set(‘view engine’, ‘pug’);
app.set(‘views’, ‘./views/pug’);

app.use(session({
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true,
cookie: { secure: false }
}));

app.use(passport.initialize());
app.use(passport.session());

fccTesting(app); // For fCC testing purposes
app.use(‘/public’, express.static(process.cwd() + ‘/public’));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

myDB(async client => {
const myDataBase = await client.db(‘database’).collection(‘users’);

app.route(‘/’).get((req, res) => {
res.render(‘index’, {
title: ‘Connected to Database’,
message: ‘Please log in’
});
});

passport.serializeUser((user, done) => {
done(null, user._id);
});

passport.deserializeUser((id, done) => {
myDataBase.findOne({ _id: new ObjectID(id) }, (err, doc) => {
done(null, doc);
});
});

}).catch(e => {
app.route(‘/’).get((req, res) => {
res.render(‘index’, { title: e, message: ‘Unable to connect to database’ });
});
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(Listening on port ${PORT});
});

//This image is of my URL for the cluster.

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36

Challenge Information:

Advanced Node and Express - Implement the Serialization of a Passport User

On Replit you have to use the secrets settings.


Just as an aside, don’t use the sample.env for your environment variables at all.

1 Like

Does it want me to put my MONGO_URI and connection string into secrets?

On another note, I made a .env file and pasted my variables there and I’m now getting this.

MONGO_URI is the key and your connection string is the value.

Did you remember to add SESSION_SECRET as well? You are using that variable with the session middleware.


You can ignore the deprecation warning.

1 Like

I did add SESSION_SECRET as well.

I just refreshed the Webview and the database is now connecting. Thank you so much for your help!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.