amrnn90 / breeze-nuxt Goto Github PK
View Code? Open in Web Editor NEWAn application / authentication starter kit frontend in Nuxt3 for Laravel Breeze.
License: MIT License
An application / authentication starter kit frontend in Nuxt3 for Laravel Breeze.
License: MIT License
Hello, if we want to access to validationErrors in onError function in usesubmit, we need to use NextTick, to fix it we need to swap this lines from:
options?.onError?.(e);
validationErrors.value = e.data?.errors ?? {};
to:
validationErrors.value = e.data?.errors ?? {};
options?.onError?.(e);
Hello, i'm trying to use "useLarafetch" inside of my composable called "useDocuments", i'm trying to get documents from laravel in lazy mode, to show skeletons while documents loads. The function is called like it doesn't be async function, so i can't use loadingDocuments var because it is always false, any suggestion? Is an error that i can't see in useLarafetch? Maybe is running always in ssr? If i use useLarafetch directly in setup funcion it works, but when i try to use in my composable with lazy option, it works like ssr.
useDocuments.ts
export const useDocuments = () => {
const documents = useState<Pagination<Document> | null>(
"documents",
() => null,
);
const document = useState<Document | null | undefined>(
"document",
() => null,
);
const isEditing = useState<boolean>("isEditing", () => false);
const loadingDocuments = useState<boolean>("loadingDocuments", () => false);
const getDocuments = async () => {
loadingDocuments.value = true;
try {
const { data, pending } = await useLarafetch<Pagination<Document>>(
"/documents",
{
lazy: true,
},
);
loadingDocuments.value = false;
documents.value = data.value;
return { data, pending };
} catch (error) {
console.log(error);
}
};
documents.vue
const { getDocument, documents, getDocuments, isEditing, loadingDocuments } =
useDocuments();
await getDocuments();
how do i send a blob image using submitRequest? I tried to set Content-Type header as multipart/form-data but it didnt work
I have followed the instruction in the read me, but end up getting the error 500 "fetch failed ()".
@at async Module.$larafetch (my-project-path-/utils/$larafetch.ts:33:12)
Hello, i'm looking that initCsrf function is called always, so if i make a post request e.g to /blogs, always first is called /sanctum/csrf-cookie. I think that CSRF route only should be called in login and register but i could be wrong. I want to develop a module where the user can save while he writes with a short debounce, so the user can make many requests while he is tipyng, i wouldn't like that if the user make 50 requests they be 100 by always make initCsrf. According laravel docs:
Laravel automatically generates a CSRF "token" for each active [user session](https://laravel.com/docs/10.x/session) managed by the application.
To authenticate your SPA, your SPA's "login" page should first make a request to the /sanctum/csrf-cookie endpoint to initialize CSRF protection for the application:
During this request, Laravel will set an XSRF-TOKEN cookie containing the current CSRF token. This token should then be passed in an X-XSRF-TOKEN header on subsequent requests
If we have e.g. forms or routes that we need to be protected if we are guest users, maybe we can use like this, to not use only in login and register:
if (
process.client &&
["post", "delete", "put", "patch"].includes(
options?.method?.toLowerCase() ?? "",
) &&
!token
) {
await initCsrf();
token = useCookie(CSRF_COOKIE).value;
}
Hi, firstly I want to say thank you for this awesome repo. I have used this in my project and it works great. But when I want to create a new project with nuxt, I need to copy the code from this repo to my new project. It would be cool if someone could make this a nuxt module.
It would help a lot of people who want to use this in their nuxt project.
Thank you.
Hello @amrnn90 ,
I'm trying to make the NuxtLoadingIndicator to be work with useLarafecth / $larafetch, so I can get the laoding progress shown for each fetch request to the Breeze API.
Due to the nature of NuxtLoadingIndicator itself, seems like the solution for now is to add hook call for fetch options to the event of
onRequest and onResponse, as being mentioned in this example
nuxt/nuxt#14221 (comment)
Been tried to add such options in useLaraftch / $larafetch to no avail, So if you can direct me to where should I add those options to useLarafecth / $larafetch, that would be helpful.
Pardon for any unclear explanation or misconception, since I'm very noob for this frontend Vue/Nuxt things 🙏
The developers of this application should please contact me. I need help with the deployment. Your effort will of course be paid. Please contact me within the next 7 days if you are interested.
Question: Can your module also handle 2 different top domains and do I have to work with subdomains because of sanctum.
Your software runs with 2 TopLevel Domain I have no CORS problems only the login does not work error message "CSRF token mismatch.".
I have noticed the following.
After comparing the request csrf-cookie (both tokens) and the next request login compared
the cookies in the request cookies are correct but in the response cookies the laravel_session are not the same.
So the problem is that laravel_session has lost the value of csrf-cookie (laravel_session) when calling the login page in response cookies.
there is a different value in the laravel_session.
Would using subdomains solve the problem.
With kind regards
Dieter Deutsch
Hello,
I've been using your breeze-nuxt and there is an issue that unauthorized data can be called without token option in header. As long as referer option is set in the header, any unauthorized data can be called.
Thanks
"message": "CSRF token mismatch.",
"exception": "Symfony\Component\HttpKernel\Exception\HttpException",
"file": "D:\xampp\htdocs\example-app\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php",
"line": 428,
"trace": [
{
"file": "D:\xampp\htdocs\example-app\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php",
"line": 399,
When accessing https://example.com/login
an error occurs
message "CSRF token mismatch."
exception "Symfony\Component\HttpKernel\Exception\HttpException"
file "/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php"
line 396
I don't have a Cors problem, how can I send the token with the post call.
I have noticed the following.
After comparing the request csrf-cookie (both tokens) and the next request login compared
the cookies in the request cookies are correct but in the response cookies the laravel_session are not the same.
So the problem is that laravel_session has lost the value of csrf-cookie (laravel_session) when calling the login page in response cookies.
there is a different value in the laravel_session.
Many thanks for a little help.
Yours sincerely
Dieter
With CSRF and relying on laravel cookies, it appears this can not be opened up to cross-domains. The best setup is to have API and UI on their own isolated domain names. a root and a subdomain. Unless I'm missing something, it doesn't appear that this will work.
in $larafetch.ts no cookies can be read out. it is undefined when transferring to the login page, therefore the error
message "CSRF token mismatch."
Thanks for the help
$larafetch does not work with the installed
"axios": "^0.21.2", from @vercel in your program. It brings the 419 error or the response dismatch token.
According to research at Axios, I could not find the error in any other package.json file.
One question, can I install axios version 1.5.1 and if so where should I install axios, in the breeze-nuxt?
Is there a guide where this problem with your package has already been addressed and solved. I have been researching for a long time how could I solve the problem? I think everyone in the production environment should have this problem.
More Infos to the error:
axios/axios#6047
Can I use 2 different top-level domains or do I have to work with subdomains? I use different https://frontend.com and https://backend.com domains. The cookie values that are generated do not match. I get a 419 error message in the browser.
I have noticed the following.
After comparing the request csrf-cookie (both tokens) and the next request login compared
the cookies in the request cookies are correct but in the response cookies the laravel_session are not the same.
So the problem is that laravel_session has lost the value of csrf-cookie (laravel_session) when calling the login page in response cookies.
there is a different value in the laravel_session.
Thank you very much for your help.
Kind regards
Dieter Deutsch
Hello,
Since recently none working due error message;
"[nuxt] [request error] [unhandled] [500] [nuxt] A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function." Any idea? I did this on a fresh installation.
Regards,
Kohlzz
Hello, i'm trying to use $larafetch in server api /server/api/submit.ts
, but i can't. Im trying to import like this import { $larafetch } from "../../../utils/$larafetch";
But i'm getting an error
[nuxt] [request error] [unhandled] [500] useRouter is not defined
at $larafetch (./utils/$larafetch.ts:29:1)
I'm trying to check if user is authenticated directly from laravel server, to after run any code in nuxt server.
I am using Docker w/ Laravel Sail to power the back-end. However, I cannot seem to make a request towards the API using this codebase.
This is the error:
500
request to http://localhost:9000/api/user failed, reason: read ECONNRESET ()
(I used port 9000 for the back-end because I already have another environment that exists on port 8000)
If I visit http://localhost:9000/api/user myself then I can see that the environment is running OK (I get redirected to /login
). I have also tried the solutions mentioned at #3 but unfortunately the same error keeps getting thrown.
Fresh install.
throw error on server cause issue (@amrnn90 what is the purpose of throw error here. thanks)
Hey there,
I have modified my backend and instead of just returning the token
when the login route is called my backend returns such a response:
{
"message": "You have been successfully logged in.",
"data": {
"user": {
"id": 4,
"username": "123",
"email": "[email protected]",
"products_count": 13,
"comments_count": 646,
"saved_products_count": 1,
},
"token": "104|Hd2TOnxPMTFcMdbN3MyLFsidmUGfiaety6ioBJkP4b6ae563"
}
}
This means my login token
cannot be retrieved by larafetch
just by response.token
. I need to change it to response.data.token
as the token
is part of the data
object.
But how do I do this? I cannot find a single line of code where you set the Laravel Sanctum auth token to the header of the user. I can only see lines which are about the XSRF-Token
.
I highly appreciate any kind of help!
Kind regards
Great starter kit but on production server I get an error when logging in. Login is not possible. Database and user is available.
Login error on production machine, cors works but I get the error
Local with host: localhost:3000 and localhost:8000 everything local works great.
On the production server I have different hostnames but the cors problem is solved. Everything works but I can't log in.
Thanks for the help.
With kind regards
Dieter
Hi there,
first, thank you for this package! Had a problem with importing ohmyfetch in your wrapper $larafetch and submitRequests. Think its now just 'ofetch' instead of 'ohmyfetch', at least its working.
greetings
A really great starter kit, but unfortunately I get the error
when executing
npm run build
node .output/server/index.mjs
Listening on http://[::]:3000
[nuxt] [request error] [unhandled] [500] useEvent is not defined
Compiling also does not work when I reload the system.
npm run dev works fine.
Thanks for the help.
Not a problem, just though maybe you could guide me to the best way to do what I'm trying to do.
All of my responses are wrapped in data
, e.g a response could look like this:
{
"data": [
{ "id": 1, ... },
...
],
"total": 120,
"page": 1,
...
}
So when I do a request using useLarafetch
, to get the actual data
attribute, I'm adding a computed property like this:
const { data, pending } = await useLarafetch(`/api/posts`)
const posts = computed(() => {
return data.value.data
})
It would be nice if I could do this somehow, or make a custom fetch composable or something that would do something like this, but I'm not sure exactly how at the moment:
const { data: posts, page, total, pending } = await useLarafetch(`/api/posts`)
If you're able to point me in the right direction to do this, that would be great, thanks!
Hi, I'm having an issue using the Auth aspect of this starter.
If I register or login, I am always getting an 'Unauthenticated' error from the API.
Curious if anyone has run into this issue as well and knows a fix.
i am trying to make a very simple guest middleware which will check if the user is already logged in dont let him visit the log in page thats it , i tried your code and implemented mine too but its still throwing the same error which i mentioned above
but whenever i am tryna use this middleware it just doesn't work, i have already wasted 6 hours on this straight.
when i use the let checkUser = authStore.isLoggedIn
the value is always true for logged in users which i have debugged inside console.log but when i hard code the value of the checkuser variable then it works perfectly i dont know what is the problem here
here's what i am getting when i am using stores : the middleware waits for a sec and then redirects and gives me some errors which look like this :
also when i try to do the inverse it works i dont know how but i dont want that , you can see at the below code and the comment
import { useAuth } from "../composables/Auth.js"
export default defineNuxtRouteMiddleware(async(to,from) => {
const nuxtApp = useNuxtApp()
const authStore = useAuth(nuxtApp.$pinia);
let checkUser = ref(authStore.isLoggedIn);
console.log(checkUser.value)
// this doesn't work
if ((to !== '/') && (checkUser.value)) {
return navigateTo('/')
}
// this works somehow with the inverse condition but i dont want that
if ((to !== '/') && !(checkUser.value)) {
return navigateTo('/')
}
// if (to !== '/' && !authStore.user?.id) return navigateTo("/", { replace: true });
});
Continuing #17
Hi, sorry for the late response. I'm using your library on a side project which I work on once a month.
I'm not getting any errors on the terminal. In the browser's console, I get this warning:
Hi, I just discovered a small bug, but I don't know what would be the correct way to solve it.
Reproduction:
Open two windows with a session started (with a user logged in), then close the session in one window and access the other window and switch to another page that uses useLarafetch.
The line that detects if the response has a 401 or 419 status redirects you to the login, but the user.value still has the same value, since you closed the session in the other window, so the login returns to the page that is configured to redirect.
Possible solutions:
Add a refresh in the useLarafetch or maybe only user.value = null?
const { refresh, user } = useAuth();
async onResponseError({ response }) {
const status = response.status;
if ([500].includes(status)) {
// eslint-disable-next-line no-console
console.error("[Laravel Error]", response.statusText, response._data);
}
if ([401, 419].includes(status)) {
// Refresh user
await refresh();
// Or
user.value = null;
return navigateTo("/login");
}
Also we can add to guest middleware, but is can cause slow load page when we try to use lazy fetch.
Hey man, thank you for putting some time into this repo; it's incredible.
I'm using the verified middleware in my pages in Nuxt, except in login, of course. But when I refresh the page, I'm redirected to the login page and then back to home. Any idea of why this is happening?
Do you want me to provide any snippets from my code?
Thank you for your time
Hi!
I have a problem and I don't know why it happens.
In local everything works fine, but in production I have mydomain.com (frontend) and api.mydomain.com (backend). When I try to login I get 419 ("message": "CSRF token mismatch.").
Do you know why?
Thanks and good job! :)
I am not sure if I am missing something with how this should work.
I pulled down a fresh version of this repo installed everything and connected it to my Laravel backend.
Everything works great, I can login, logout, use middleware etc. I can navigate around to pages and everything works.
But if I reload the page on welcome for example which has auth middleware I am taken back to the login page.
Is this the expected behaviour and I need to add some code to persist the login?
Hello, i checking that when i use custom subdomain with laravel valet like api.domain.test and webapp.domain.test, the XSRF TOKEN is duplicated with different domain, causing 419 errors in login page and other requests.
.env laravel
SANCTUM_STATEFUL_DOMAINS=webapp.domain.test
SESSION_DOMAIN=.domain.test
Nuxt:
I have simple component with useAsyncData, and is the same with useLarafetch, and when i make call, new XSRF TOKEN is issued in my cookies but with subdomain, so, i have two XSRF TOKENS, one with .domain.test and one with webapp.domain.test.
Also i'm checking that it only succeed when i use a layout
page1.vue
<script lang="ts" setup>
const { data: uniqueId } = await useAsyncData("uniqueId", () => {
return $larafetch("/user/unique-id");
});
</script>
<template>
<div>
<div>Hello</div>
<NuxtLink to="/page2">Page 2</NuxtLink>
</div>
</template>
Also, to reproduce, you need to add page1 and page 2, and move between pages with NuxtLink
page2.vue
<script lang="ts" setup>
</script>
<template>
<div>
<div>Hello from page 2</div>
<NuxtLink to="/page1">Page 1</NuxtLink>
</div>
</template>
After move between pages 2 o 4 times, check cookies and you should see two XSRF TOKENS
Hi, thank you for this composables. I have a problem. When refreshing a page after succes auth, im redirecting to /login first and then to /main route then. I can add some preloader to not see the login page while im authorized.
Hello, when i make npm run build
to test app like to deploy, and node .output/server/index.mjs
i'm getting 500 useEvent is not defined, from $larafetch.
I'm looking that in nuxt.config.ts we have
export default defineNuxtConfig({
modules: ["@nuxtjs/tailwindcss"],
runtimeConfig: {
public: {
backendUrl: "http://localhost:8000",
frontendUrl: "http://localhost:3000",
},
},
imports: {
dirs: ["./utils"],
},
experimental: {
asyncContext: true,
}
});
And in the useEvent nitro docs says that we need nitro key in nuxt.config.ts, but it doesn't work yet:
export default defineNuxtConfig({
nitro: {
experimental: {
asyncContext: true
}
}
})
If i remove all 'event' references from $larafetch it works correctly.
let token = useCookie(CSRF_COOKIE).value;
// on client initiate a csrf request and get it from the cookie set by laravel
if (
process.client &&
["post", "delete", "put", "patch"].includes(
options?.method?.toLowerCase() ?? "",
)
) {
token = await initCsrf();
}
let headers: any = {
accept: "application/json",
...options?.headers,
...(token && { [CSRF_HEADER]: token }),
};
if (process.server) {
const cookieString = useRequestHeaders(["cookie"]).cookie;
headers = {
...headers,
...(cookieString && { cookie: cookieString }),
referer: frontendUrl,
};
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.