I have created a website using SvelteKit. I am using form action for handling login form.
src/routes/(beforeAuth)/login/+page.svelte
have login form
<form use:enhance method="post" action="/login?/login">
<label>Username:</lable>
<input type="text" name="username" />
<label>Password:</lable>
<input type="password" name="password" />
<Button text="Sign In" type="submit" />
<form>
src/routes/(beforeAuth)/login/+page.server.js
have login action
export const actions = {
login: async ({ cookies, request }) => {
const data = await request.formData();
let body
try{
body = await api.post("account/login/", {
username: data.get('username'),
password: data.get('password')
});
}catch(err) {
return {
message: "username or password is not vailid",
login: false
}
}
if (body.status === 401) {
return fail(401, { tryAgain: true })
}
if(body.status == 400) {
return {
message: body.data.message,
login: false
}
}
if(body.status == 200) {
const value = btoa(JSON.stringify(body));
cookies.set('jwt', value, { secure: false, path: '/', maxAge:60 * 60 * 6 });
redirect(307, '/my-profile')
} else {
return {
message: "username or password is not vailid",
login: false
}
}
},
logout: async ({ cookies, locals }) => {
cookies.delete('jwt', {path:'/'});
locals.user = null;
},
};
This login form and action is woring fine. But now I want to send query parameter via form action. So I tried set action to /login?/login?redirect=some-path
e.g.
<form use:enhance method="post" action="/login?/login?redirect=some-path">
This is giving me error
SvelteKitError: No action with name 'login?redirect' found
What is right way to send query parameter via form action in SvelteKit?
The Redirects subsection of the Form/Action docs makes use of query string params to perform an optional redirect (which is your aim as well), so we know this is possible.
Since the form name is derived from a special nomenclature (i.e. by prefixing a query parameter with /
), it is natural to assume that in the URL /login?/login
, the ?
marks the beginning of the query string, and thus an extra ?
would be taken literally (hence the error you get in return where your backend looks for an action named login?redirect
).
I would assume the correct format is thus /login?/login&redirect=some-path
where ?
marks the beginning of the query-string, /login
is the first parameter (and because of /
is parsed as an action name), &
is a standard query separator, and redirect=some-path
should then be properly parsed.
As for accessing and using that parameter properly, I again refer you to the link above (using the url
accessor and the searchParams
attribute).