How to make FastAPI perform SSR for Vue 3?
P粉004287665
2023-08-26 21:31:32
<p>According to Vue's SSR documentation, it is possible to render an application using node.js and return it using an Express server. Can FastAPI do the same thing? </p>
<p>Or is using Jinja2 templates or SPA the only solution? </p>
<h3>Question: </h3>
<ul>
<li>No SPA: Helps with SEO</li>
<li>No SSG: Too many pages will be generated. Some need to be generated dynamically. </li>
<li>No Jinja2/Python templates: Node modules will not be built, bundled, and served. All modules must be served via a remote package CDN. </li>
</ul>
<p>I have a feeling that maybe changing the Vue 3 delimiter and then building the project and serving the files as Jinja2 templates would be the solution, but I'm not sure how it would work with Vue's router. I know that the <code>/dist</code> folder can be served on the default route and then use a catch-all that can be used to show the files that actually exist. </p>
<h3>Possible solutions</h3>
<pre class="brush:py;toolbar:false;">@app.get("/", response_class=FileResponse)
def read_index(request: Request):
index = f"{static_folder}/index.html"
return FileResponse(index)
@app.get("/{catchall:path}", response_class=FileResponse)
def read_index(request: Request):
path = request.path_params["catchall"]
file = static_folder path
if os.path.exists(file):
return FileResponse(file)
index = f"{static_folder}/index.html"
return FileResponse(index)
</pre>
<h3>Question</h3>
<ul>
<li>If there was a way to do SSR using FastAPI and Vue 3, what would it be? </li>
<li>If there is no direct way, how to combine Vue's built-in <code>/dist</code> with Jinja2 templates to provide dynamic pages? </li>
</ul></p>
There are several options available, such as Nuxt.js, Quasar, and Gridsome, which provide support for SSR via FastAPI and Vue 3.