Skip to content

Commit

Permalink
🚀 Send JWT via cookie
Browse files Browse the repository at this point in the history
  • Loading branch information
maqsudtolipov committed Sep 3, 2024
1 parent d704f79 commit adc80ef
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 0 deletions.
10 changes: 10 additions & 0 deletions server/controllers/authController.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,20 @@ exports.register = catchAsync(async (req, res) => {

const user = await User.create(data);

// Generate jwt
const token = jwt.sign({ id: user._id }, process.env.SECRET, {
expiresIn: '1d',
});

// Generate a cookie
const cookieOptions = {
expiresIn: '1d',
httpOnly: true,
secure: true,
withCredentials: true,
};
res.cookie('access-token', token, cookieOptions);

res.status(200).json({
status: 'success',
token,
Expand Down
23 changes: 23 additions & 0 deletions server/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"description": "",
"dependencies": {
"bcryptjs": "^2.4.3",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.19.2",
Expand Down
2 changes: 2 additions & 0 deletions server/server.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const cookieParser = require('cookie-parser');
const dotenv = require('dotenv');
dotenv.config({ path: './.env' });

Expand All @@ -13,6 +14,7 @@ const app = express();
// Middlewares
app.use(cors());
app.use(express.json());
app.use(cookieParser());

// Routes
app.use('/api/v1/auth', authRouter);
Expand Down

0 comments on commit adc80ef

Please sign in to comment.