Sessions in Node JS

前端 未结 10 804
北海茫月
北海茫月 2021-01-07 23:46

How can I maintain my SESSIONS in Node JS ? E.g I want to store UserID in SESSION using Node Js. How can I do that in Node JS ? And can I use that Node JS SESSION in PHP too

相关标签:
10条回答
  • 2021-01-08 00:16

    You don't need to to it by yourself. There are some amazing modules in nodeJS that handle this kind of things for you.

    You can use session middleware from express, as suggested before.

    However, I'd recommend you to use passportJS. This module does the authentication part for you, has a lot of strategies that you could integrate in your website (login with facebook, google, twitter, etc etc), and deals with all the session stuff automatically, using serializeUser() and deserializeUser() functions whenever you need to.

    You can take a look at this here, within session section: http://passportjs.org/docs/configure

    0 讨论(0)
  • 2021-01-08 00:17

    ExpressJS has official session middleware, it is also the current de-facto standard web framework for Node.js.


    If you wish to implement session support on your own, this is how the implementation is normally done, upon every request:

    1. Check if cookie contains a session ID
      • If not, create a session object that is either stored in memory, on file, or in a database (or a combination of those), and set the session id in the response cookie to match this object's identifier.
      • If the cookie does contain a session ID, locate the session object by the ID.
    2. Provide the obtained/created object from step 1 as the persisted session object for the request.

    You will also have to implement some timeout mechanism, so that after a while the session objects are deleted, at least from memory.

    0 讨论(0)
  • 2021-01-08 00:17

    You can handle the session in two-way.

    1. Using express-session
    2. Using JWT web token and handle own session(Token Based Session handling).

    I think token based session handling is more important rather than using express-session. You will get a problem when you scale your server and also a problem some single device login situation.

    For Checking I have Token Based Session Hanling node js folder structure.You can check. It may be helpful

    0 讨论(0)
  • 2021-01-08 00:19

    Let me divide your question in two parts.

    1. How can I maintain my SESSIONS in Node JS ?
    Answer: Use express-session middleware for maintaining SESSIONS

    2. can I use that Node JS SESSION in PHP too ?
    Answer: Yes, you can use that session in PHP too but keep in mind you have to store that session in database.

    0 讨论(0)
提交回复
热议问题