9

I need to save jwt-token in local-storage through nodejs after the user has logged in (has been authorized ).

After I check if the user/password is correct in my controller - I save generated token in local storage. As it stands I can't reference window as it doesn't exists.

ReferenceError: window is not defined 

This is how I'm currently trying to do it.

...
      payload = {
        sub: user.email,
        role: user.role
      };

      token = jwt.sign(payload, jwtSecretKey, {expiresIn: '60m'});

      window.localStorage.setItem('token', token);

      res.status(200).render('index' , {
        user: user,
        token: token
      });
...
5
  • 5
    Do you know what the difference is between a client and a server?
    – Amit
    May 12, 2016 at 9:28
  • So... Why are you trying to do client stuff on the server?
    – Amit
    May 12, 2016 at 9:35
  • I wondered if it was possible. I'll quote the person from one of the linked threads "There are plenty of modules that bring the DOM to the server-side, webkit to the server-side, so I was curious if someone had brought localStorage to the server-side."
    – Paran0a
    May 12, 2016 at 9:37
  • You can access the local storage using jquery or angularjs at clientside. so, put your code there :) May 12, 2016 at 9:42
  • 1
    Hey! @Paran0a. Can you check answers to your question. Mine may be correct :))
    – sçuçu
    Aug 27, 2018 at 9:04

3 Answers 3

17

You cannot save to localStorage on Node.js, but you can do it on a browser, possibly after sending from a server, for your case from a server on Node.js.

You should send the token from the server (running on Node.js) to the client (browser) which has a window object, having the localStorage and related getItem and setItem methods, you can reference from your JavaScript code for client (browser). Node.js does not have any window to reference. So, by referencing it in Node.js code is a ReferenceError hinting program code is referring to a thing that is not defined, undefined, you have encountered.

Just put it into a cookie and send, or send it via a json response. Then on the client browser save it into window.localStorage.

following is the examples code for the latter way; sending via a response:

// SERVER-SIDE Code
// say `app` is your app server on node.js
// this is a url handler on your server-side code
// you just have sent your user credentials from a browser
// typically via a form in the body of your http request
app.post('/auth', function (req, res) {
  // you may have here some jwt token creation things
  // ...
  // and send it as your response to the client (probably a web browser) ..
  // with your prefrred name as the key, say 'my_token', ..
  // where you will save it to localStorage (ie. window.localStorage)
  res.json({my_token: 'asdfgh-anything-jw-token-qwerty'})
})

  // CLIENT-SIDE Code (may be a web browser)
  // You have just sent a request to the server..
  // ..with user credentials for authentication in the request body
  // in the request body may be a window.FormData object or a json etc.
  http.post('auth', userCredentials)
    // probably the request mechanism you make http..
    // ..requests asynchronously, maybe using a library,..
    // ..will return a Promise, and you will have a similar code below.
    .then(response => response.json())
    .then(responseJson => {
      // set localStorage with your preferred name,..
      // ..say 'my_token', and the value sent by server
      window.localStorage.setItem('my_token', responseJson.my_token)
      // you may also want to redirect after you have saved localStorage:
      // window.location.assign("http://www.example.org")
      // you may even want to return responseJson or something else or assign it to some variable
      // return responseJson;
  })
8
  • Hi can you give me an example how to send it via json response
    – Kannan T
    Jul 10, 2017 at 7:00
  • here use this fiddle as an example, and you can always ask back
    – sçuçu
    Jul 10, 2017 at 13:48
  • Hi bro i figured that out before thanks for this help however am struggling to redirect the page can you help me in that?
    – Kannan T
    Jul 10, 2017 at 14:02
  • 1
    @kannan if you will send your token to the client inside a request without a cookie, do your redirect on the client side and just after the line above code sets the window.localStorage. Otherwise, you will loose your token, data sent from server side, between full page reload that will happen when you redirect your page. To make your web page redirect after this set operation use window.location, by just assigning it to the address you will redirect to like window.location.assign('http://example.com/')
    – sçuçu
    Jul 10, 2017 at 14:10
  • understood bro am sending the token without a cookie jsfiddle.net/vqbfxrnj here is the nodejs login code.Here is my front end login code jsfiddle.net/97boc34q
    – Kannan T
    Jul 10, 2017 at 14:32
1

If you mean html 5 localStorage, there's no such a thing since node.js is a server-side technology. Html 5 localStorage is a client side feature supported

refer How to access localStorage in node.js?

3
  • Yeah, I'm talking about that storage. I've seen few tutorial where people recommend to save generated token into cookies or local storage. So If I want to save it from node I should use cookies?
    – Paran0a
    May 12, 2016 at 9:29
  • Yes can use cookies for the same May 12, 2016 at 9:30
  • You can use cookies or a json response.
    – sçuçu
    May 12, 2016 at 9:31
1

In the client call to /login use xmlhttpresponse object, then add an event listener for 'load'. This will give the client the responseObject where you have added the token. Then in the event listener put your localStorage code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.