DEV Community

Zak Miller
Zak Miller

Posted on • Originally published at

How to Serve Vue with Nest

Want to serve a VueJS app from a NestJS backend? Here's how you do it.

Create a new Nest app

Install the Nest CLI

npm install -g @nestjs/cli

Create the NestJS app

nest new nest-with-vue

Install the dependencies

cd nest-with-vue
npm install

Verify it's all working properly

First, run it (this will watch the folder so we won't have to restart the server as we make changes):

npm run start:dev

Then, hit it (in a separate terminal window):

curl localhost:3000

You should get Hello World!.

Set it up to serve static content

Install the package:

npm install --save @nestjs/serve-static

Use the package


import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ServeStaticModule} from '@nestjs/serve-static'; // New
import { join } from 'path'; // New

  imports: [
    ServeStaticModule.forRoot({ // New
      rootPath: join(__dirname, '..', 'client/dist'), // New
    }), // New
 controllers: [AppController],
 providers: [AppService],
export class AppModule {}


import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.setGlobalPrefix('api'); // New
  await app.listen(3000);

We're moving all the existing endpoints to under /api, and then serving the static content in the ./client/dist folder (which doesn't exist yet) when someone hits the root (in this case localhost:3000).

Also note that the name client here could be anything. It's just the folder where we're going to put the Vue app.

Verify that the controller endpoint moved

Now, if we hit the previous endpoint:

curl localhost:3000

You should get {"statusCode":500,"message":"Internal server error"}.

But if you hit the new /api endpoint:

curl localhost:3000/api

You get Hello World! again.

Now we just have to create the Vue app in that ./client/dist folder.

Create the VueJS app

Install the Vue CLI:

npm install -g @vue/cli
# OR
yarn global add @vue/cli

Create the app:

vue create client

Build the app:

cd client
npm run build

This will put all the static files in ./client/dist, right where the Nest app will be looking for them.

Verify that Nest is serving the compiled Vue app

curl localhost:3000

You should get something that looks like:

<!DOCTYPE html><html lang=en> ... <strong>We're sorry but client doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> ... </html>

Which is the HTML being served by the Vue app.

Open it up in your browser and you'll see it's working!

Vue screenshot

Closing words

That's it. You can find the complete code here.

Top comments (0)