Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Express API with JWT
var express = require('express')
, jwtMiddleware = require('express-jwt')
, bodyParser = require('body-parser')
, cookieParser = require('cookie-parser')
, cors = require('cors');
// We pass a secret token into the NodeJS process via an environment variable.
// We will use this token to sign cookies and JWTs
var SECRET_TOKEN = process.env.SECRET_TOKEN;
// Create the app server
var app = express();
// For each request, provide wildcard Access-Control-* headers via OPTIONS call
// For each request, parse request body into a JavaScript object where header Content-Type is application/json
// For each request, parse cookies
app.use(cookieParse());'/login', (req, res) => {
var email =
, password = req.body.password;
// Some how get the user.
// This doesn't have to be sync... you could write the token gen and response in a callback
var user = findUserSomehow(email, password);
// Using SECRET_TOKEN, create a token string that contains the user's _id from the database.
var token = JWT.sign({
_id: user._id
// Send the response with 200 status code (ok) and the user object + the token
// The client will send the token with every future request
// against secured API endpoints.
user: user,
token: token
// Secure "protected" endpoints with JWT middleware
app.use('/protected', jwtMiddleware({
secret: SECRET_TOKEN, // Use the same token that we used to sign the JWT above
// Let's allow our clients to provide the token in a variety of ways
getToken: function (req) {
if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') { // Authorization: Bearer g1jipjgi1ifjioj
// Handle token presented as a Bearer token in the Authorization header
return req.headers.authorization.split(' ')[1];
} else if (req.query && req.query.token) {
// Handle token presented as URI param
return req.query.token;
} else if (req.cookies && req.cookies.token) {
// Handle token presented as a cookie parameter
return req.cookies.token;
// If we return null, we couldn't find a token.
// In this case, the JWT middleware will return a 401 (unauthorized) to the client for this request
return null;
// A simple protected route for demo purposes
app.get('/protected/data', function (req, res) {
console.log(req.user); // => { _id: <Some ID attached to the JWT signed in the login route above> }
text: 'Hello world!'
app.listen(80); // Listen on port 80

This comment has been minimized.

Copy link

@Slntswrd Slntswrd commented May 6, 2018

Have you tested that code gist?
Because I see something that i can't undestand for example:

4:  , cookieParser = require('cookie-parser')
21: app.use(cookieParse());

at line 21 you write: app.use(cookieParse());
But at line 4 you have imported : cookieParser = require('cookie-parser')
One is "cookieParse" the other one ins "cookieParseR"

And at line 33:

33:  var token = JWT.sign({

you use "JWT" but is the only occurence in code, there are some dependency injection somewhere else?

those code works on your machine?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.