DEV Community

loading...

NextJS + TypeORM Entities

tomburgs profile image Toms Burgmanis ・2 min read

If you've ever used TypeORM before, you probably know that it has a wonderful sync feature which has a look at your entity files and updates your database schema accordingly.

This is very convenient as it eliminates the dull work of creating & updating table migrations.

Typically all you'd need to do is set TypeORM settings synchronization: true and pass an entities property with a path to your entity definition directory.

Not Next.js friendly

This does not work nicely with Next.js for 3 reasons:

  1. If you pass it a path to the directory with the non-transpiled files, node simply won't be able to execute them.
  2. Due to how Next.js compiles server-side code, your entities will end up under the actual api route file, not in their own separate files.
  3. Even if you placed each entity under the pages/api directory (bad idea btw), in development mode they won't be compiled until requested through http.

Solution

Since we don't want to import and pass each entity file to TypeORM manually, we can go to our good friend Webpack for help.

First thing we have to do is tell Webpack to automatically include each of our entity files.

/*
 * Our entity files end with '.entity.ts' and live under the
 * 'api/database/entities` directory.
 */
const context = require.context('api/database/entities', true, /\.entity\.ts$/);
Enter fullscreen mode Exit fullscreen mode

Now, context has the keys method we can use to get the array of files it found under the entities directory.

/*
 * e.g ['./user.entity.ts', './profile.entity.ts', ...]
 */
const entityFileNames = context.keys();
Enter fullscreen mode Exit fullscreen mode

Finally, we can import these files by calling context method itself.

/*
 * We're calling `.default` to get the default export.
 */
const entities = entityFileNames.map(file => context(file).default);
Enter fullscreen mode Exit fullscreen mode

Now all is left to do is to pass them to createConnection

createConnection({
  ...
  synchronization: true,
  entities
});
Enter fullscreen mode Exit fullscreen mode

Et voilà, that's all we need to sync our entity files in Next.js with TypeORM.

Note: If you're using TypeScript, you'll need to add webpack's type definitions: yarn add -D @types/webpack-env.

Conclusion

I hope this helped someone!

If you have any questions, feel free to ask.

Happy syncing ❤️

Discussion (0)

pic
Editor guide