-
-
Notifications
You must be signed in to change notification settings - Fork 7.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add documentation on how to serve static files #402
Comments
Hi @testos944, |
Well, not if you don't want to use a view engine but serve only a plain html file :) But I guess I can juste use res.sendfile('public/index.html'), I will try this out. |
Yes, that's true. I'll provide a small example without any engine soon 🙂 |
For anyone wondering :
If you put your index.html file in the public folder, it should be good to go |
@kamilmysliwiec, is there any way to have a global catch all route ? I want to catch all routes (except those defined in my modules/controllers), something like that in expressjs:
|
If you're interested in serving static files, here's a nice way to do it with fastify and fastify-static. This solution assumes that your static files are in the root of the project, in the folder dist/public. Then, add the following lines to: main.ts async function bootstrap() {
const app = await NestFactory.create(AppModule, new FastifyAdapter());
app.useStaticAssets({
root: path.resolve(__dirname + "../dist/public")
});
...
} app.controller.ts @Get()
root(@Res() res) {
res.sendFile("index.html");
} This will serve your main index.html as well as any other assets on the root path "/". |
@kamilmysliwiec if you're still working on examples I would love to see an example where nestjs serves both static files and json responses depending on the route. I would love to serve both my react app and the json needed from the server! |
@Cspeisman here is an example (in src/main.ts) import { join } from 'path'
import { renderFile } from 'ejs'
import { NestFactory } from '@nestjs/core'
import { AppModule } from './app.module'
(async () => {
const app = await NestFactory.create(AppModule)
app.
engine('html', renderFile).
setBaseViewsDir(join(__dirname, '../views')).
useStaticAssets(join(__dirname, '../views/public'), {
index: false,
redirect: false
})
await app.listen(process.env.PORT || 3000)
})() and in app.controller you render the file like so: import { Get, Controller, Render } from '@nestjs/common'
import { AppService } from './app.service'
@Controller()
export class AppController {
constructor(private readonly appService: AppService) { }
@Get()
@Render('public/index.html')
root(): Promise<object> {
return this.appService.root()
}
} |
@ovidiup13 Your solution is great, works on dev mode, (localhost:8080), but does not when I need to run it on a aws server. I have checked everthing: port, firewall and others, but nestjs does not load an index.html file |
@calebeaires hmm... That's weird. It depends on how you configured to access the service on aws. Have you tried with other routes to return, for example, JSON? |
@Cspeisman main.ts app. app.controller @get() export class AppService { What should go in appService? |
@Cspeisman object with all the data you want to put into the view using ejs template rendering. |
This answer explains how by using an exception filter, a wild card can be achieved: https://stackoverflow.com/questions/49879274/nestjs-default-wildcard-route/49917487#49917487 |
And if you create an ExeptionFilter and add it to the app.module.ts all paths will return index.html. You just need to take care of the routing on the client(React, Angular, etc) `import {ArgumentsHost, Catch, ExceptionFilter, NotFoundException} from "@nestjs/common";
}` |
Edit: As you can find in the comment below for Nest 6 and newer I recently came to the same situation where I needed to serve an SPA (React) from within a NestJS application that also served an express legacy application. But I did not wanted to loose the 404 on false API requests, luckily all my API requests were prefixed with redirect-client.filter.ts
main.ts
|
@CanKattwinkel I really want to use your example but nestjs/core "has no exported member 'HTTP_SERVER_REF'. Do you have a solution for this? Nest.js version: 6.1.1 |
@jesben I think that got changed from v5 to v6. I guess we should mention that in the docs const app = await NestFactory.create(AppModule);
const refHost = app.get(HttpAdapterHost);
const httpServer = refHost.httpAdapter.getHttpServer(); |
what is the Typescript Type of @Get('*')
public reactApp(@Res() res: Response): any {
res.sendFile('index.html');
} |
|
Hello, I am new to Nest, but I think that you are looking to serve a SPA application (Angular or similar). I am setting up something similar with this example: |
Hello, i want to share images but the router redirect me everytime on an index file :'( @Module({
imports: [
PrismaModule,
ServeStaticModule.forRoot({
rootPath: join(__dirname, '..', 'public'),
serveStaticOptions: {
index: false,
},
}),
] If you have any suggestions :) |
@ncbtart You could use app.useStaticAssets and NestFastifyApplication if it's possible. That helped me to serve my static assets, stylings, images and js files |
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. |
I'm submitting a...
The documentation is very well written and very useful; however I think an example of serving a static file would be a huge plus.
I'm trying to serve an Angular App bundled with a NestJS backend, and see no clear way to do that. An example serving a static html file would help a lot.
The text was updated successfully, but these errors were encountered: