Nuxt generate is keeping my dynamic routes working - vue.js

I am using nuxt for a static webapp, using "mode: spa" and "nuxt generate".
The docs say that dynamic routes do not work with this, but my app (/dist) still works on static server after generating, even though the routes aren't generated. I cant figure out why.
Before generating, my routes look like:
export function createRouter () {
return new Router({
mode: 'history',
base: '/',
routes: [
{
path: "/",
component: _36d3a217,
name: "index"
},
{
path: "/:focus",
component: _fbe76838,
children: [
{
path: "",
component: _6d415767,
name: "focus"
},
{
path: ":view",
component: _19cdee48,
name: "focus-view"
}
]
}
],
fallback: false
})
}
Now, the generated /dist does not create the /focus directory as expected...But In my app, I am using route URL params to query an API and it still works.
ie a route like below, the component will use "thisFocus" and "thisView" as parameters in the API:
/thisFocus/thisView
Since the dynamic routes do not exist in /dist, i would think that this would not work anymore. So how does the app still use those URL params successfully without the routes existing?
Edit: another more simple way to ask maybe: why can i still access /:focus/:view route.params even though the routes dont exist?

If you use nuxt generate, you usually want a statically generated page. That means, having one HTML file per route which contains actual HTML which was rendered by the server.
You want that because it'll give you the "best of both worlds", good SEO, faster TTI and so on but without running a Node.js server all the time. (Further read)
If you want a traditional SPA, you typically have just one index.html file with almost no HTML but Javascript included.
Source code of a typical SPA
Dynamic routes
When you "pre-render" (=== statically generate) your page, Nuxt needs the information which routes it should render. For routes without parameters that's easy (e.g. about.vue or posts/index.vue). As soon as there are dynamic parameters, Nuxt can't "guess" them.
So yes, dynamic routes are "ignored" because Nuxt don't know what do to with them except you tell Nuxt which routes to pre-render.
These routes will then be generated. This does not mean that you can't access dynamic routes that you didn't provide to Nuxt. You can still access them (example: a post that doesn't exists) and the requests will be parsed (depending on your server config and whether you have generate.fallback enabled or not) but you lose the SEO benefit and see a spinner as the fallback file is equivalent to the index.html from your traditional SPA.
Source: Replied on github by manniL who is a nuxt core member

Related

How to bypass router for certain URLs with Vue Router?

I'm using Vue Router with Vue 3 in a web application I'm working on, and have a 'catch all' route defined as the last route:
{
path: "/:catchAll(.*)*",
component: () => import("pages/Error404.vue")
},
This is picking up everything, though, including calls to the /api/ back end (although not via Ajax), and even things like '/test.csv', which is a link to a CSV file in the root directory.
How can I bypass the router for certain URLs, allowing them to be treated as regular requests?
Incidentally, I don't know whether this is relevant, but the application in question is a PWA built using Quasar. When I make the call to e.g '/test.csv', I see a request for 'service-worker.js' with a 304 response code in my nginx access log, confirming that the request is being handled by the router rather than nginx.

Error 404 on a page that exists and that works fine through internal link

I created a website with several pages on Vue.js.
Everything is working fine locally, but when I deploy to Heroku, all pages are only working when I click on an internal link in my menu that redirects to the corresponding page (using router push).
When I try to access directly /any-page from the browser I get a 404 with a message saying "Cannot GET /any-page" whereas the same page is displayed correctly via a click on a link.
As I mentioned when I locally serve my app I don't have this problem.
I really can't see where this can come from, thanks in advance for your help.
There's a deployment guide specifically for Heroku in the official Vue CLI documentation.
You'll quickly notice the relevant information:
static.json
{
"root": "dist",
"clean_urls": true,
"routes": {
"/**": "index.html"
}
}
For SPA's (Single Page Applications), you'll want to point every route to the index. Vue router will take care of navigating to the proper page.
Heroku is serving the contents of your Vue build folder. Since Vue builds the app as a single index.html file, only the main route works.
Vue doesn't actually navigate to the route, it rather rewrites the the browser url using the history API and handles the loading of the new route.
You could use one of these options:
OPTION 1
You could use mode: "hash" to fix routes when reloading the page. However this will add a # before every route.
const router = new VueRouter({
mode: "hash",
routes: [...]
})
OPTION 2
Write an Node.JS (eg Express) app that routes every request to your index.html file. This is called a middleware
Reference: https://router.vuejs.org/guide/essentials/history-mode.html#example-server-configurations

Vue direct URL is not working, only router-link click

This may be a known Vue routing thing that I am totally missing.
So I have a .vue file that uses the url /hardware.
Here is the routing
{
path: "/hardware",
name: "Hardware",
component: () =>
import(/* webpackChunkName: "hardware" */ "../views/Hardware.vue")
},
Going to /hardware directly using a link on an external site or typing it in the address bar does not work, gives me Page Not Found.
But clicking on this link in my nav bar does work.
<router-link to="/hardware">Hardware</router-link>
Am I missing something super obvious that I missed when I was learning routing? Is this because it is a single page application? Thanks in advance for any help.
Adding that I do have history mode on, wondering if this is the issue?
const router = new VueRouter({
mode: "history",
base: process.env.BASE_URL,
routes
});
Following back from comments to answer (Netlify) Vue-router works locally and not at the hosting/deployment side like Apache/Nginx/Firebase Hosting as:
1)
Pretty-URL / Hashbang dilemma in SPA.
The server needs to redirect when your Vue project enabled history mode. in apache, just some redirect rules needed to be done via .htaccess similarly, so as most of the hosting services included Netlify (you need to check the routes redirect rules at Netlify there). As server page not found, telling us that your route doesn't have actual files under that specified /route at their side.
Previous thread: Vue Router return 404 when revisit to the url
2) If your project for Multi-page-mode instead of going hashbang SPA, Your Vue Project needed to be configured little bit further: Either via SSR or pre-rendering static files before deployment
It could be that your browser is adding a trailing slash to giving you "/hardware/" which does not match your route. In the past, I had created an alias to match both routes such as "/hardware" and "/hardware/".
I faced the same issue nowadays and decided to share my thoughts with the community.
You can easily resolve the bug just by removing mode: "history" from the Router. Then it will be automatically replaced by the hash (#) in your URLs. It's going to work then even if you'll use a direct link in the browser.
However, based on the latest SEO recommendations History mode is more preferable because URLs without # are better tracked by Google.
If you would like to save History mode, you need to enable history mode on your server. I use Express middleware and the solution in my case is next:
const express = require('express');
const history = require('connect-history-api-fallback');
const app = express();
app.use(history());
app.use(express.static('src'));
app.get('/', (req, res) => {
res.sendFile('src/index.html');
});
app.listen(3000, () => console.log('server started'));

Laravel's intended() with vue router

I am working on a project and am struggling with redirecting to intended location after login.
The problem is that Laravel does not include Vues route (anything after #/...) so it always redirects me only to 'domain.com/'
I am using laravel routing only for 'login' 'logout' and '/' and rest of the app is single page utilizing vue routing.
Users of the app are receiving notification emails when they need to take action. Those email contain links to requests where their action is required (e.g. domain.com/#/request/3413). Of course they need to login to be able to access that so they are redirected to login page by laravel (domain.com/login#/request/3413)
After successful login I am trying to redirect them with
return redirect()->intended('/');
But it redirects them to 'domain.com/' instead of 'domain.com/#/request/3413'
Is there any way to make laravel include vues route in that redirect?
Thanks a lot!
So after some excruciating research I have found out that anything after # is handled by browser meaning that server does not see it so you cant access it in your PHP code. I found out thanks to this thread: Getting FULL URL with #tag
I am unsure if that part of the request is not even sent to server but it seems like that and is even pretty logical to me that it would be so.
So to solve this I changed the link sent to user via email to something like this
domain.com/?request=3413
This way I can access it in my PHP code and put together the redirect link after successfull login.
You can remove the # in the URL in Vue Router by enabling History Mode like so:
const router = new VueRouter({
mode: 'history',
routes: [...]
})
You will need to direct all your requests to where you app lives. If your backend is Laravel, you can define a catch-all route in your routes/web.php file
Route::get('/{any}', 'SpaController#index')->where('any', '.*');
The caveat to this is that the server will no longer return 404s for paths that are not found so you will have to create a NotFoundComponent to display on your Vue app if a path is not found.
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '*', component: NotFoundComponent }
]
})
Read the Vue Router History Mode Documentation for more info

Vanity urls for files in Vue 2.1

Reading through the Vue Router docs this seems like it should be pretty simply, but I can't get it to work.
First I tried to use the file in S3
{
path: '/rules',
redirect: 'https://s3.amazonaws.com/itsclarke/vue-project/pdfs/rules.pdf'
}
This resulted in the redirect being appended to localhost:8080/#, so I got localhost:8080/#/https://s3.amazonaws.com/...
Also tried using the same approach with the static folder:
{
path: '/rules',
redirect: '../../static/rules.pdf'
}
This kept the path relative, but inestead of showing the pdf, it took me to localhost:8080/#/static/rules.pdf which isn't the path. localhost:8080/static/rules.pdf is what I need. This needs to use hash mode as well.
Using alias mode isn't much help either because I don't have components for these files. I know these redirects can be down on the server level, but I want to do it within Vue Router.
I don't think this is possible out of the box with vue-router - it expects the redirect value to be another client-side route, not a server-side url. I think your best bet would be to use a beforeEnter guard on your /rules route to redirect (using window.location) to the url. Alternatively, you could have your /rules route return a component that displays the pdf in an iframe.