I recommend to use one of two commonly methods. I describe how to make it with fetch object, on client and express framework on server.
1. Setting the token in the HttpOnly cookie
In server controller
module.exports.checkUser = (request, response) => {
const { token = null } = (/token=(?<token>[^;]*)/.exec(request.headers.cookie) || {}).groups || {} // Or better use cookie-parser
crudModel.verifyUser((result) => {
if (Array.isArray(result) && result.length > 0) {
if(result[0].email == request.body.email && result[0].password == request.body.password){
let jwtToken = jwt.sign({
email: result[0].email,
user_id: result[0].uid
}, "mohit_pandey_1996", {
expiresIn: 300000
});
response.cookie('token', jwtToken, {
httpOnly: true,
// secure: true // - for secure, https only cookie
});
response.render('dashboardView'); // - now we don't need to appear token to the view, because it automatically appears in cookies in each request
}
} else {
console.log('Invalid Username or Password');
response.render('errorView');
}
}, token); // <- pass token
}
On the client side (on page), if you are use fetch for requests, you need to add the credentials parameter
function makeRequest(url) {
return fetch(url, {
credentials: 'include'
})
}
More about pros and cons of this method you can read this
https://stackoverflow.com/a/39833955/9051045
2. Using token in request header with saving it into localStorage
Example (client script) in html > head
function makeRequest(url, method) {
var jwtToken = localStorage.getItem('token')
var headers = {}
if(jwtToken) {
headers['Authorization'] = 'Bearer ' + jwtToken
}
return fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors',
headers: headers
})
}
This function make request with token, when it was setup in localStorage
Your Controller function: (server)
module.exports.checkUser = (request, response) => {
var {token = ''} = (/Bearer\s+(?<token>.*)/.exec(request.get('Authorization') || '') || {}).groups || {}
crudModel.verifyUser( (result) => {
if (Array.isArray(result) && result.length > 0) {
if(result[0].email == request.body.email && result[0].password == request.body.password){
let jwtToken = jwt.sign({
email: result[0].email,
user_id: result[0].uid
}, "mohit_pandey_1996", {
expiresIn: 300000
});
response.render('dashboardView', { token : jwtToken});
}
}else{
console.log('Invalid Username or Password');
response.render('errorView');
}
}, token); // <-pass token
}
View(ejs) :
<script>
localStorage.setItem('token', "<%= JSON.stringify(token) %>"); // <- setup token into localStorage, (but i think it's not good place for that, and would be better get token with another authorization request)
</script>
<!-- Your code below -->
<li class="nav-item active">
<a href="/user/home?authorization=Bearer "+data>Home
<span class="sr-only">(current)</span>
</a>
</li>