Vue workbox, dont cache specific dynamic routes - javascript

How can I disable certain routes from getting cached by the service worker?
Eg I have a URL: https://someurl.com/emailValidate/1231231?email=some#email.com - The thing after emailValidate is a dynamic ID, which is why I dont want all things on the route /emailValidate and after that should not be cached by the SW...
I've tried adding this to the vue.config, but doesnt seem to do much:
module.exports = {
pwa: {
workboxPluginMode: 'InjectManifest',
workboxOptions: {
swSrc: './src/sw.js',
swDest: 'service-worker.js',
globIgnores: ['**/emailValidate', '**/passwordReset']
},
runtimeCaching: [
{
urlPattern: new RegExp('/emailValidate'),
handler: 'NetworkFirst'
},
{
urlPattern: new RegExp('/passwordReset'),
handler: 'NetworkFirst'
}
],
navigateFallbackBlacklist: ['/emailValidate', '/passwordReset']
}
};

Related

How to use proxy with vite (vue frontend) and django rest framework

So, you know when you access a view with django rest api on the browser, you get an html page, and when you send something like an ajax request, you get the json? I'm trying to figure out how to mess with the proxy setting for vite, but I can't find a single decent documentation around it. I want to redirect '/' to 'http://localhost:8000/api', but there's really weird behavior going on.
If I have a route on localhost:8000/api, I can do:
//vite.config.js
export default defineConfig({
plugins: [vue()],
server: {
proxy: {
//Focus here
'/api': {
target: 'http://localhost:8000',
changeOrigin: true,
rewrite: (path) => { console.log(path); return path.replace('/^\/api/', '') }
}
}
}
})
//todo-component.vue
export default {
data() {
return {
todos: []
}
},
components: {
TodoElement
},
beforeCreate() {
//Focus here as well
this.axios.get('/api').then((response) => {
this.todos = response.data
})
.catch((e) => {
console.error(e)
})
}
}
This will return the json response as expected. However, if I try to make it so that '/' routes to 'localhost:8000/api/', like this:
export default defineConfig({
plugins: [vue()],
server: {
proxy: {
//change here
'/': {
target: 'http://localhost:8000/api',
changeOrigin: true,
rewrite: (path) => { console.log(path); return path.replace('/^\/api/', '') }
}
}
}
})
import TodoElement from "./todo-element.vue"
export default {
data() {
return {
todos: []
}
},
components: {
TodoElement
},
beforeCreate() {
//change here
this.axios.get('/').then((response) => {
this.todos = response.data
})
.catch((e) => {
console.error(e)
})
}
}
It just spews out the html version of the api view, but with no styling, with a bunch of errors
No idea what to do. If someone could explain how this proxy works, i'd really love it. I don't want to keep writing "api/", and it'd be really valuable if I can manage to understand how this works.
You are a bit confusing things and I will try to show you why.
If you redirect root path / to /api, every request sent to your app running at http://localhost:3000 will be forwarded to http://localhost:8000/api. It mean that you will not be able to serve anything from the running app, but you will get an answer from the configured endpoint (localhost:8000/api) for every request.
To understand easily what is going on, keep in mind that this vite config option (server.proxy) act like a reverse proxy. As example, I take the favicon.ico resource of your app.
With your current configuration, when from your browser you try to access your app, the /favicon.ico (and all other resources) is then loaded from http://localhost:8000/api/favicon.ico and not anymore from your app running at http://localhost:3000/favicon.ico.
This explain all the errors in the console. Again, for example, /static/rest_framework is loaded from http://localhost:8000/api/ and not http://localhost:3000/.
The documentation is quite clear, it's just a matter of understanding what a http-proxy is. To get more information you can head to https://github.com/http-party/node-http-proxy#core-concept

Angular SSR, Dynamic Page Won't Load - Status 504

Code: http://github.com/dbots-co/website
Directly connecting to a dynamic route (dashboard, bot page), seems to not work. However, directly connecting to docs does work.
This only happens when using Angular 10 Universal SSR.
Not Working: https://dbots.co/bots/774811448576573480
Working: https://dbots.co/docs/get-started
bot-page.component.ts:
async ngOnInit() {
await this.service.init();
this.user = this.service.getBot(this.id);
this.bot = this.service.getSavedBot(this.id);
if (!this.user || !this.bot)
return this.router.navigate(['']);
this.seo.setTags({
description: this.bot.listing.overview,
titlePrefix: this.user.username,
titleSuffix: 'DBots',
url: `bots/${this.id}`
});
this.analytics.botPageView({ botId: this.user.id });
this.themeService.setNavbarBackground('var(--background-secondary)');
document
.querySelector('.navbar')
.setAttribute('style', `margin-bottom: -5px;`);
}
app-routing.module.ts:
const routes: Routes = [
...
{ path: 'bots/:id', component: BotPageComponent },
...
];

Vuejs-nuxt (SSR Mode) not able to get UserUUID through getter inside plugins. It shows undefined for GetUserUUID

I'm using SSR mode in my vuejs-nuxt project. So whenever I attempt to call socket event, I need to pass userID to that socket from the store. The GetUserUUID getter works fine in all other APIs. But it fails only in case of calling from the "plugin/socketio.js" file. I need some help to get data from the getter.
plugins/socketio.js
export default async ({ store, $axios }) => {
console.log(store.getters.GetUserUUID,"Current User UUID which is showing undefined");
function listenStock({ channelName, eventName }, callback) {
console.log("callback",callback);
window.Echo.channel(channelName).listen(eventName, callback);
}
//Fetch user data
listenStock(
{
channelName: `BalanceUpdateEvent.${store.getters.GetUserUUID}`,
eventName: "BalanceUpdateEvent"
},
({ data }) => {
console.log(data, "socket data");
try {
store.dispatch("setUserBalance", data.data.userBalance);
} catch (ex) {
console.log(ex);
}
}
);
nuxt.config.js
plugins: [
{ src: '~/plugins/socketio', mode: 'client' }
]
echo: {
plugins: ['~/plugins/socketio.js']
},
This image is a result of console.log(store.getters), But I need to access GetUserUUID.
Please try it in the nuxt.config.js
export default {
plugins: [
....
{ src: '~/plugins/socketio.js', mode: 'client' }, // only on client side
...
]
}
That run your plugin in client side

Next Js Custom Routes and SSR

I am using apollo with next and recently I noticed that custom routes breaks SSR. Usually if you navigate through pages apollo caches the query and when you are on the page the next time, it serves everything from cache. However with custom routes, the cache is never used.
I also noticed that when I click on these pages, an error flashes in the console. But it goes away very fast and I wasn't able to copy it here.
Server.js
//
server.get('/about-us', (req, res) => app.render(req, res, '/about'));
server.get('/about', (req, res) => res.redirect(301, '/about-us'));
Menu Click Handler
const navigate = link => () => {
Router.push(link);
};
Menu Items
export const menu = [
{
name: 'Home',
url: '/',
},
{
name: 'Catalogs',
url: '/catalogs',
},
{
name: 'Shop',
url: '/shop',
},
{
name: 'Wholesale',
url: '/wholesale',
},
{
name: 'About Us',
url: '/about-us',
prefetch: true,
},
{
name: 'Contact Us',
url: '/contact-us',
prefetch: true,
},
];
Based on a suggestion from nextjs spectrum I tried prefetching custom pages in the TopNav Component but it didn't work.
const prefetch = url => {
if (process.browser) {
console.log('prefetching these urls', url);
Router.prefetch(url);
}
};
useEffect(() => {
menu.forEach(menuItem => {
if (menuItem.prefetch) {
prefetch(menuItem.url);
}
});
}, []);
I was able to figure out the problem. This is not really well documented but you need to prefetch the component. So for my case instead of prefetching /about-us I should have prefetched /about.
That's why there is as prop in the link component. Nextjs 9 just got released which fixes this issue.
https://nextjs.org/blog/next-9#dynamic-route-segments
For nextjs 9 you can save your file as [pid].js and it will catch all paths in a specific route. i.e for /products/test-product you have to create folder products and inside that add [pid].js.
I needed to query for product based on slug so I added this and voila, I have access to the slug inside my component.
Product.getInitialProps = async ({ query }) => {
return { slug: query.pid };
};
These issues were pretty frustrating before next 9 but it's heavily simplified and it helped me fully remove server.js.

hapi-swagger disables my routes

Below is the glue manifest I use to fire up the server:
var Config = require('../config.json');
var internals = {
manifest: {
connections: [
{
host : Config.host || process.env.IP,
port : Config.apiPort || process.env.PORT,
labels : ['api']
}],
plugins: {
'./decorate': [{ 'select': ['api']}],
'hapi-auth-jwt': [{ 'select': ['api']}],
'./authentication': [{ 'select': ['api']}],
'./controllers': [{ 'select': ['api']}],
'./models': [{ 'select': ['api']}],
'./api': [{ 'select': ['api']}],
good: {
opsInterval: 5000,
reporters: [
{ 'reporter': 'good-console', 'events': { 'log': '*' } }
]
}
}
}
};
if (!process.env.PRODUCTION) {
internals.manifest.plugins['blipp'] = [{}];
internals.manifest.plugins['good'].reporters[0].events['ops'] = '*';
}
module.exports = internals.manifest;
As soon as I add 'hapi-swagger' to the list of plugins the server stops responding to the routes defined in the ./api file. None of the routes work. Is the the right way to add hapi-swagger to the glue manifest or am I doing something absurd?
EDIT: Below is the api.js
exports.register = function (plugin, options, next) {
plugin.dependency('controllers');
plugin.dependency('models');
var Controllers = plugin.plugins.controllers.handlers;
var Models = plugin.plugins.models.models;
plugin.bind({
models: Models
});
plugin.route([
{ method: 'GET', path: '/token', config: Controllers.Membership.token },
{ method: 'GET', path: '/', config: Controllers.Home.status },
{ method: 'GET', path: '/nodes', config: Controllers.Node.search },
{ method: 'GET', path: '/services', config: Controllers.Node.services },
{ method: 'GET', path: '/createnodetree', config: Controllers.Loader.createNodeTree }
]);
next();
};
exports.register.attributes = {
name: 'api',
version: require('../package.json').version
};
This happens if you try to use hapi-swagger without either including the documentation view dependencies or properly disabling documentation support. From the docs:
If you want to view the documentation from your API you will also need to install the inert and vision plugs-ins which support templates and static content serving. If you wish just to used swagger.json without the documentation for example with swagger-codegen simply set options.enableDocumentation to false.
You didn't show how you are adding the hapi-swagger plugin but you simply need to add 'enableDocumentation': false to options wherever you define that. You can find examples at the link above.

Categories

Resources