Set it up

npm install express webpack isomorphine

The minimum required dependencies to start working with isomorphine are a connect-like server(like Express), webpack, and of course the isomorphine loader.

For organising our code for this particular scenario I recommend the following directory structure:

APP_NAME

|--app <--- isomorphic code goes here.

|--models

|----Entity1

|--------create.js

|--------update.js

|--------read.js

|--------OtherFunctionality.js

|----index.js

|--server

|----index.js

|package.json

|webpack.config.js

|index.js

Now set up the webpack.config.js

var webpack = require('webpack');



module.exports = {

entry: {

...

},

output: {

...

},

module: {

preLoaders: [

{

loaders: ['isomorphine']

}

]

}/** UPDATE: This is no longer needed in latest version,

plugins: [

new webpack.DefinePlugin({

'process.env': {

ISOMORPHINE_HOST: '"http://myhost.com"',

ISOMORPHINE_PORT: 8000

}

})

]**/

};

Please do note the double quotes(“”) on the ISOMORPHINE_HOST environment variable. I spent an hour or so trying to find why the set up was breaking due this.

UPDATE: This previous specification of port and host is no longer needed in the latest version. Please refer to the repos README for more details.

Now that we have everything configured. Lets write some code to actually take advantage of the library.

Use it now

Most of the apps I have built using express, or any other server framework, include the data models in the server folder. It made a lot of sense, after all, it is the only place where you actually get access to your data models by making request to a database or to a third party web service, or just by having access to the file system.

But now, since we will have to access them from 2 different places(Client & Server) it is a good idea to move the data layer outside of the server because that would helps us to separate responsibilities.

Now here is the interesting part. Lets create an entity and add some functionality:

As you see, there is nothing different from a regular JavaScript function. It takes some parameter, performs some logic, and returns a result.

The real magic resides in the /models/index.js file:

// /models/index.js import isomorphine from 'isomorphine'; export default isomorphine.proxy();



At this point your models are ready to be used by any server side code. Just import the models like so:

And in your app/index.js (this is what will be called in the client side)

As I am sure you noticed, we are calling the methods the same way. This is really isomorphic data fetch.

Finally just bundle and run your server: