Tuesday 6 June 2017

User profile in isomorphic applications

I'm currently in the process of adding login, plus a set of advanced features related to login, to a website using React, Redux, Express and Node. For the actual login, I'm using Passport, with Facebook, Google and Twitter strategies. After getting the required token, it's sent to AWS Cognito Federated Identities to get synchronized data for the user. Data from the website is also synchronized back to Cognito whenever needed.

After the user has logged in, I can construct a complete user profile on the Node server, but now what?

// server.jsx
// imports
.............

// variables
.............

var userProfile;
// logging the user with Passport and adding it to the profile
.............

app.use((req, res) => {
    // I can do whatever I want with the profile here
    .............

    // handling the request and creating an initial state ..
    .............
}

Back in the days, this would be fairly easy to solve using either session variables (Java/C#) or cookies (JS), but in isomorphic applications it's not quite that simple. Let's say that the user gets access to profile.jsx via routes after logging in: A cookie (set via client-sessions for example) is only available when the jsx file is run on the client; it's not accessible whenever it's server rendered. Custom code appears to be required even when using things like isomorphic-cookie or universal-cookie, which pretty much defeats the purpose of an isomorphic application. I also thought of using Redux, but Redux appears to only have an initial state on Node, which doesn't help much.

// Profile.jsx
import React , { Component } from 'react';
import Cookies from 'universal-cookie';

class Profile extends Component {
    // Stuff
    .............

    render() {
        // Would love to be able to access to the profile without custom code like this
        if (typeof window != 'undefined' && window.document) {
            const cookies = new Cookies();
            console.log(cookies.get('user'));
        }
    }

So is there a smooth way of handling user profiles or other variables that you want access to at all times, without writing a huge amount of custom code for each scenario? It seems most tutorials and examples handle this sort of thing exclusively either on the server or the client, which would require a re-write of the website in this particular case.

Isomorphic applications are fairly straight forward in most cases, but the complexity really shoots through the roof when authentication, profiles and so on is introduced, so I would greatly appreciate any feedback on the matter.



via MortenTZ

No comments:

Post a Comment