How to Upgrade an Existing NestJS Project

Updated: January 2, 2024 By: Guest Contributor Post a comment

Introduction

Keeping your NestJS project updated is crucial for security, performance, and accessing the latest features. This guide walks you through the steps to seamlessly upgrade your existing NestJS project.

Assessing Your Current Environment

Before proceeding with an upgrade, it’s essential to understand your project’s current state. Ensure you have a backup and check the post-upgrade changes. Run the following commands to assess the versions of Node.js and NestJS:

node -v
npm list @nestjs/core

Upgrading Node.js

If the Node.js version is outdated, head over to nodejs.org and download the latest version. Note compatibility between your Node.js version and the NestJS target version.

Upgrading the NestJS CLI

Start by globally updating the NestJS CLI:

npm install -g @nestjs/cli@latest

Updating the Project Dependencies

Use the NestJS CLI’s upgrade command within your project directory:

nest update

This will attempt to update all NestJS-related packages.

Handling Breaking Changes

Check the latest NestJS version’s changelog for breaking changes and refactor your code accordingly. Follow best practices and update incrementally if you’re multiple versions behind. Use TypeScript’s strict mode to help identify potential issues:

// tsconfig.json
{
  "compilerOptions": {
    "strict": true
    // ... other options
  }
}

Updating Other Dependencies

Use npm outdated to view which packages are outdated and update them carefully, ensuring compatibility with your NestJS version.

Testing

After updating your packages, run your test suite to ensure everything is functioning as expected. If issues arise, consult the documentation and consider the impact of major upgrades on custom code or third-party packages.

Consider Using Docker

For those already using Docker or considering it, containerizing your app ensures a consistent environment, making upgrades smoother. Example Dockerfile:

# Use an official Node runtime as a parent image
FROM node:latest

# Set the working directory
WORKDIR /usr/src/app

# Install app dependencies
COPY package*.json ./
RUN npm install

# Bundle app source
COPY . .

# Expose port and run the application
EXPOSE 3000
CMD [ "npm", "run", "start" ]

See also: How to set up NestJS with Docker Compose.

Managing Environment-Specific Configurations

Remember to manage environment-specific configurations that may affect your upgrade. Use .env files and NestJS configuration services for dynamic values.

Finishing Touches

Lastly, check deprecations, remove unused packages with npm prune, and verify environmental variables.

Conclusion

Upgrading your NestJS project ensures you reap the benefits of the newest features and vital security patches. Always review changelogs, maintain good test coverage, and document custom configurations to alleviate the process.