Home > front end >  What is proper way to store code/functions that are used by both the frontend and backend?
What is proper way to store code/functions that are used by both the frontend and backend?

Time:11-19

My frontend Reactjs app is stored in one repository. My backend Node.js app is stored in another repository.

There are some functions used by both. Where should store those functions so that both repositories can access them?

CodePudding user response:

You can create a library that exports all of the functions you'll be needing, then publish it to NPM and add it to the dependencies of both projects' package.json. With NPM you can set your packages as private, too, in case you don't want your code/package to be publicly available.

The starting point would be to create a directory with all the functions you need, export them all in an index.js, and run npm init to create a package.json for your new project. You'll be guided for naming and assigning a version number, then publish with npm publish (you may need to create an account and run npm login first). Then in your frontend and backend projects you simply npm install <your-package> like any other npm package.

Your project directory may be as simple as...

myFunctions.js
index.js
package.json

myFunctions.js:

export const functionA = () => {
  return "a"
}

export const functionB = () => {
  return "b"
}

index.js:

export * from './myFunctions.js'

package.json (can be created with npm init:

{
  "name": "my-functions",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Then in the directory run npm publish, and in your other projects you can run npm install my-functions.

And finally, in your other projects:

import { functionA } from 'my-functions';

// ...

functionA() // returns "a"

CodePudding user response:

Creating a separate NPM package for your helper functions can certainly be a good solution, but I find them somewhat annoying to maintain across different repositories. I tend to try and avoid them.

There are certainly some functions in your application that do have purpose on both the front- and backend, but I would encourage you to look at these carefully to see if that logic can be the responsibility of one or the other (backend or frontend).

For example; if you have a function to parse a date and format it in a very specific way for your app then you can have that function live solely in the backend and leverage it to pass back the already converted value to the frontend - avoiding the burden of maintaining it in 2 places or in a separate package that then needs to be updated in 2 repositories.

Sometimes there's just no getting around it though, but I found that in most cases I can split them accordingly.

  • Related