I’m working on a project with a Flutter frontend and a Node.js + TypeScript backend. I’m having issues getting all the user info when they log in. I followed a tutorial but can’t get the same results.
Here’s what I’m getting:
{
"message": "Login successful",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
But I want something like this:
{
"user": {
"id": "user123",
"username": "johndoe",
"email": "john@example.com",
"created_at": "2025-05-09T06:23:54.778Z",
"updated_at": "2025-05-09T06:23:54.778Z",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
}
My login function looks like this:
async function signIn(req, res) {
const { email, password } = req.body;
try {
const userResult = await db.query('SELECT * FROM users WHERE email = $1', [email]);
const user = userResult.rows[0];
if (!user || !await comparePasswords(password, user.password)) {
return res.status(401).json({ error: 'Wrong email or password' });
}
const authToken = generateToken({ userId: user.id });
res.json({ message: 'Login successful', token: authToken });
} catch (error) {
res.status(500).json({ error: 'Login failed', details: error.message });
}
}
How can I modify this to return the full user object with the token?
hey leo, i had similar issues. try this:
after generating the token, create a new object with user info + token:
const userResponse = {
id: user.id,
username: user.username,
email: user.email,
created_at: user.created_at,
updated_at: user.updated_at,
token: authToken
};
res.json({ user: userResponse });
this should give u the format u want. lmk if it works!
heyy leo! Have u considered using object destructuring? it’s super handy for this kinda stuff. try something like:
const { password, …userInfo } = user;
res.json({ user: { …userInfo, token: authToken } });
this way u get all the user data without sending the password. what do u think? would that work for ur project?
To return the full user object along with the token, you can modify your signIn function like this:
async function signIn(req, res) {
const { email, password } = req.body;
try {
const userResult = await db.query('SELECT * FROM users WHERE email = $1', [email]);
const user = userResult.rows[0];
if (!user || !await comparePasswords(password, user.password)) {
return res.status(401).json({ error: 'Wrong email or password' });
}
const token = generateToken({ userId: user.id });
const { password: _, ...userWithoutPassword } = user;
res.json({ user: { ...userWithoutPassword, token } });
} catch (error) {
res.status(500).json({ error: 'Login failed', details: error.message });
}
}
This approach removes the password field from the user object for security, then merges the remaining user details with the token, which will return a JSON structure similar to your desired output.