I have image displayed on my Nuxt page but anytime I navigate away from it back the image breaks and I do not know why.
I have this in my code
<img :src="baseUrl + 'storage/'+ front.featured_image" alt="post-title" />
and my script
data: () => ({
frontpage: [],
baseUrl: process.env.BASE_URL
}),
async asyncData({ $axios }) {
const response = await $axios.get('/api/frontpage')
return { frontpage: response.data.posts }
},
I have a .env file and I have the following inside it BASE_URL=http://localhost/ and I also have the following inside nuxt.config.js
env:{
baseUrl: process.env.BASE_URL || 'http://localhost/'
}
My API is built using laravel and it is loading from http://localhost/ but Nuxt keeps going back to localhost:3000 on page change.
You can check my previous answer here: https://stackoverflow.com/a/67705541/8816585
This may help
export default {
publicRuntimeConfig: {
baseUrl: process.env.BASE_URL,
},
}
Otherwise, this configuration of Axios may also help!
Related
I'm doing an Adonis v5 app with Vue 2 as frontend.
My problem is, once I've build Vue frontend into public adonis folder. If I access to a speficic route writing it into the top browser searcher, I get the E_ROUTE_NOT_FOUND from Adonis.
I do think that adonis is trying to search the route into the router of the server and not into the Vue router. Althought adonis it's configured to use static files and the first frontend page works:
Vue router.js:
Vue.use(VueRouter);
const routes = [
{
path: "/",
redirect: { name: "acceso" },
},
{
path: "/acceso",
name: "acceso",
component: SignupView,
meta: { guestAllow: true },
}];
const router = new VueRouter({
mode: "history",
routes,
});
Adonis routes.ts (It shouldn't affect as the have a prefix:
Route.group(() => {
Route.group(() => {
Route.post("register", "AuthController.register");
Route.post("login", "AuthController.login");
}).prefix("auth");
Route.group(() => {
Route.get("logs", "LogsController.index");
}).middleware("auth:api");
}).prefix("/api");
Adonis static.ts:
import { AssetsConfig } from '#ioc:Adonis/Core/Static'
const staticConfig: AssetsConfig = {
enabled: true,
dotFiles: 'ignore',
etag: true,
lastModified: true,
maxAge: 0,
immutable: false,
}
If I write localhost:3333 on the browser I redirects to /access (Correct)
But if I refresh the page, or browse manually the same route, the error shows
Any idea of what could it be?
Thank you for your time.
After looking some other projects on internet, I've seen that if you use mode: "history" on vue-router it pops the error.
So I've tried to comment this line and now I can refresh the page without E_ROUTE_NOT_FOUND error.
Frontend Vue router.js:
const router = new Router({
//mode: "history",
routes,
});
I'm trying to setup navigation guards in my Nuxt app to redirect users to the login screen if they are not authenticated via Firebase Authentication. When the user attempts to navigate my router middleware is redirecting them successfully, but on page load they are not being redirected.
I did realize that the middleware is not even being fired on page load. I found a recommendation to try a plugin to handle the redirect on page load, but it is not working. Calling router.push from within the plugin does not redirect the user.
Here are a few notes on my setup. This is being deployed to firebase hosting directly as a SPA with no SSR. It's using the Nuxt-Firebase module with Firebase Authentication service.
// nuxt.config.js
target: "server", // server here works when I deploy to firebase, but I also tried static
ssr: false,
middleware: ["auth"],
plugins: [
"~/plugins/auth.js",
],
modules: [
[
"#nuxtjs/firebase",
{
services: {
auth: {
initialize: {
onAuthStateChangedMutation:
"authData/ON_AUTH_STATE_CHANGED_MUTATION",
onAuthStateChangedAction: "authData/ON_AUTH_STATE_CHANGED_ACTION",
subscribeManually: false,
},
},
},
},
],
],
};
Here's a sample plugin I thought might solve this, but calling handleLoggedOut appears to do nothing on page load.
// --- plugin to redirect user --- /plugins/auth.js ---
export default function (context, inject) {
const auth = {
handleLoggedOut: () => {
console.log("logout handled");
context.redirect("/login");
},
};
inject("auth", auth);
}
// --- store actions --- /store/authData.js ---
actions: {
async ON_AUTH_STATE_CHANGED_ACTION(
{ commit, state, dispatch },
{ authUser, claims }
) {
if (authUser) {
// logged in
}
else {
// attempting to redirect here does not work
this.$auth.handleLoggedOut()
}
}
I'm new to Nuxt and I can't seem to find an example that solves my issue.
Any help would be greatly appreciated, thank you!
Code seems fine, But you can just use the this.$fire.auth.signOut() and you can remove the auth plugin.
Example:
// --- store actions --- /store/authData.js ---
actions: {
async signOut({ commit }, payload) {
try {
await this.$fire.auth.signOut();
// This is just a guard to avoid navigation guard error (NavigationDuplicated),
// you can remove the if block
if (!payload) {
this.$router.push('/login')
}
commit(ON_AUTH_STATE_CHANGED_MUTATION, { authUser: null})
} catch(err) {
console.log(err)
}
},
async ON_AUTH_STATE_CHANGED_ACTION(
{ commit, state, dispatch },
{ authUser, claims }
) {
if (authUser) {
// logged in
}
else {
// attempting to redirect here does not work
return dispatch('signOut')
}
}
}
The solution for redirecting users to the login on page load was to put this in my auth middleware:
export default function ({ redirect, store, route }) {
// https://nuxtjs.org/docs/internals-glossary/context#redirect
if (!store || !store.getters || !store.getters["authData/isLoggedIn"]) {
window.onNuxtReady(() => {
window.$nuxt.$router.push("/login");
});
}
}
I'm trying to prepare my portfolio website with Nextjs. I want to use gif in the site. You can find my code below. I could not find how to do it.
Next/Image does support GIF files...my first thought would be to ask if you have explicitly whitelisted a set of external domains in your next.config.js file? For the Next/Image Loader to handle external domains they must be individually whitelisted. Here are the contents of my next.config.js file.
const path = require('path');
const withBundleAnalyzer = require('#next/bundle-analyzer')({
enabled: !!process.env.ANALYZE
});
module.exports = withBundleAnalyzer({
webpack(
config,
{
dev = process.env.NODE_ENV === 'development',
isServer = typeof window === 'undefined'
}
) {
if (isServer) {
require('./scripts/generate-sitemap');
}
/**
* !dev ? preact/compat : react, react-dom on build
* reduce page weight in production by ~10%
*/
if (!dev && !isServer) {
Object.assign(
(config.resolve.alias['#/'] = path.resolve('./')),
{
react: 'preact/compat',
'react-dom': 'preact/compat'
}
);
}
return config;
},
sourceMaps: {
productionBrowserSourceMaps: true
},
images: {
domains: [
'avatars.githubusercontent.com',
'faderoom-headless.us',
'www.faderoom-headless.us',
'dtmqnbkq3btfh.cloudfront.net',
'secure.gravatar.com',
'automattic.com',
'serve.onegraph.com',
'onegraph.com',
'maps.google.com',
'lh3.googleusercontent.com',
'maps.gstatic.com',
'thefaderoom146.booksy.com',
'dev-3cqt2bq0.auth0.com',
'scontent-sea1-1.xx.fbcdn.net',
'd2zdpiztbgorvt.cloudfront.net',
'platform-lookaside.fbsbx.com',
'square-postoffice-production.s3.amazonaws.com'
]
},
future: {
webpack5: true,
strictPostcssConfiguration: true
},
i18n: {
locales: ['en-US'],
defaultLocale: 'en-US'
}
});
console.log(
'next.config.js',
JSON.stringify(module.exports, null, 2)
);
So you would have to whitelist media.giphy.com and it should work just fine. I also do recommend setting the quality prop for the Image component. Quality defaults to 75 out of 100 but I'd suggest making that closer to 100 for better UX.
Next/Image now supports gifs.
You should be able to import the gif and then toss it into the src like this
import Image from 'next/image';
import myGif from 'url'
...
<Image src={myGif} alt="my gif" height={500} width={500} />
If the url doesn't work here, it should work if you download the gif and toss it into assets.
At first I entered your code:
Your code
and nextjs gave me this as an error:
Screenshot erreur
So I added the domain 'media.giphy.com' in the configuration 'next.config.js'
This file must be added to the root of the project, at the same level as the 'pages' or 'lib' folder for example and must be called 'next.config.js':
File place screenshot
And in it you have to put this:
module.exports = {
images: {
domains: ['media.giphy.com']
}
};
Then you have to restart your next js server.
And normally you get this:
Image Screenshot
Here is some documentation to read to better understand:
https://nextjs.org/docs/basic-features/image-optimization
You can also use the prop unoptimized to serve the image as it is:
make sure you white list your domain in the next.config.js
module.exports = {
images: {
domains: ['SOURCE_IMAGE_DOMAIN']
}
};
then in your image component:
import Image from 'next/image';
<Image unoptimized={true} src={GIF} alt="the gif" height={500} width={500} />
Next documentation:
https://nextjs.org/docs/api-reference/next/image#animated-images
I'm trying to use Nuxt JS's 2.9.2 generate object to generate dynamic pages as static files using my .env file to pull a URL, I'm having difficuility in getting it to properly link up:
nuxt.config.js
require('dotenv').config();
import pkg from './package'
import axios from 'axios'
export default {
mode: 'universal',
env: {
blog_api: process.env.BLOG_API || "http://localhost:3000/articles/blogs.json"
},
/*
** Build directory
*/
generate: {
dir: 'dist-next',
routes: function () {
return axios.get(`${process.env.blog_api}`)
.then((res) => {
return res.data.blogs.map((blog) => {
return '/posts/view/' + blog.title
})
})
}
}
}
The above code, more specifically ${process.env.blog_api}, can't seem to resolve the routes, despite it working perfectly if I replace it with my own local domain.
.env
BLOG_API="http://my-local-domain.clone/articles/blogs.json"
EDIT:
Updated code with my config, http://my-local-domain.clone/articles/blogs.json is inside of static/articles
You should use dotenv module:
https://www.npmjs.com/package/dotenv
More Info about configuration with NUXT you have here:
https://samuelcoe.com/blog/nuxt-dotenv/
You probably want to set your env property in nuxt.config.js, for example:
module.exports = {
env: {
BLOG_API: process.env.BLOG_API_URL,
},
In your component, you can now use them :
makeAsyncCall({
to: process.env.BLOG_API,
})
I am using glue to spin up the hapi server so I gave the json object with connection and registration details.
I have 10 routes and i need to use authentication strategy for all the 10 routes, So followed the below steps
1) I have registered the xyz custom auth plugin
2) Defined the strategy server.auth.strategy('xyz', 'xyz', { });
3) At every route level I am enabling auth strategy
auth: {
strategies: ['xyz'],
}
How can I give below line to glue configuration object itself.
server.auth.strategy('xyz', 'xyz', { });
Glue.compose(ServerConfig, { relativeTo: baseDir }, (err, server) => {
internals.server = server;
})
One more question here is, in this line server.auth.strategy('xyz', 'xyz', { from json file}); I am reading the JSON data from a config file. When I change the data in this JSON file I dont want to restart the server manually to load the modified data. Is there any plugin or custom code to achieve this?
I figured out a general workaround for when you want to do setup that Glue does not directly support (AFAIK) and you also don't want to keep adding to index.js.
Create a plugins folder where your manifest.js is located.
Create a file plugins/auth.js (in this case). Here you will have a register callback with access to the server object and you can make setup calls that go beyond what Glue does declaratively.
Add a plugin item to manifest.js pointing to your plugin file.
in manifest.js:
register: {
plugins: [
{
plugin: './plugins/auth',
},
]
}
in plugins/auth.js:
module.exports = {
name: 'auth',
async register (server) {
await server.register([
require('#hapi/cookie'),
]);
server.auth.strategy('session', 'cookie', {
cookie: {
name: 'sid-example',
password: '!wsYhFA*C2U6nz=Bu^%A#^F#SF3&kSR6',
isSecure: false
},
redirectTo: '/login',
validateFunc: async (request, session) => {
const account = await users.find(
(user) => (user.id === session.id)
);
if (!account) {
return { valid: false };
}
return { valid: true, credentials: account };
}
});
server.auth.default('session');
},
};
(auth setup code is from the Hapi docs at enter link description here)
This is the way I have found where I can call things like server.auth.strategy() sort-of from manifest.js.
Note: Auth is not a great example for this technique as there is a special folder for auth strategies in lib/auth/strategies.