server actions
Unanswered
The King posted this in #help-forum
The KingOP
hello! I have a quick question.is it possibile to set server actions so that they only come from a specific origin?
11 Replies
The KingOP
Another question I have is why can't I pass things like formdata with files in them
@The King Another question I have is why can't I pass things like formdata with files in them
Kurilian Bobtail
You should be able to send them and they will be transferred correctly and you can retrieve them server-side.
Kurilian Bobtail
You're welcome 🙏
@Kurilian Bobtail You're welcome 🙏
The KingOP
Hey Hasan! So I tried this and it doesent work
/** @type {import('next').NextConfig} */
export const experimental = {
missingSuspenseWithCSRBailout: false,
serverActions: {
allowedOrigins: ['sourcedquick.com', 'localhost:3000'],
},
};
export const images = {
remotePatterns: [
{
protocol: 'https',
hostname: '**',
port: '',
pathname: '**',
},
],
}'use server'
import mongoose from 'mongoose'
// biome-ignore lint/style/useNodejsImportProtocol: <explanation>
import path from "path";
import sharp from "sharp";
// biome-ignore lint/style/useNodejsImportProtocol: <explanation>
import { writeFile } from "fs/promises";
import connect from "@/lib/db"
import bcrypt from 'bcryptjs'
export default async function createUser(formData){
try {
await connect()
const name = formData.get('name')
const email = formData.get('email')
const password = formData.get('password')
const file = formData.get("file");
const hash = bcrypt.hashSync(password, 8);
const UserModel = mongoose.models.users || mongoose.model('users', new mongoose.Schema({}, { strict: false }), 'users');
const lowerEmail = email.toLowerCase()
const existingUser = await UserModel.findOne({ email: lowerEmail });
if (existingUser) {
return 'error'
}
//hash
// Basically here we are creating a new user and if there is an error, we should return 'error'
// If there is no error, we should return '200'
const newUser = await UserModel.create({
name,
email: lowerEmail,
password: hash,
balance: 0
})
const buffer = Buffer.from(await file.arrayBuffer());
const filename = `${newUser._id}.png`;
const pngBuffer = await sharp(buffer)
.png()
.resize(200, 200) // Resize to a reasonable avatar size
.jpeg({ quality: 80 }) // Convert to JPEG with 80% quality for compression
.toBuffer();
await writeFile(
path.join(process.cwd(), `public/assets/avatars/${filename}`),
pngBuffer
);
return String(newUser._id)
} catch (err){
if(!String(err).includes('Error: NEXT_REDIRECT')) {
return 'error'}
}
}async function onSubmit(event) {
event.preventDefault();
if (step === 1) {
setStep(2)
return
}
setIsLoading(true)
const response = await createUser(formData)
if (response === 'error') {
toast({
variant: "destructive",
title: "Error",
description: "Email already exists",
})
setStep(1)
setIsLoading(false)
} else {
// const formDataa = new FormData();
// formDataa.append("file", formData.avatar);
// formDataa.append("id", response);
// fetch("/api/avatar", {
// method: "POST",
// body: formDataa,
// })
// .then(response => response.json())
// .then(data => console.log(data))
// .catch(error => console.error(error));
toast({
title: "Success",
description: "Welcome",
})
const formDataaa = new FormData();
formDataaa.append("email", formData.email);
formDataaa.append("password", formData.password);
await doCredentialLogin(formDataaa)
.then(() => {
window.location.reload()
setIsLoading(false)
})
.catch((error) => {
console.log('Error:', error)
window.location.reload()
setIsLoading(false)
})
}
}
const handleBack = () => {
setStep(1)
}Unhandled Runtime Error
Error: Only plain objects, and a few built-ins, can be passed to Server Actions. Classes or null prototypes are not supported.
Call Stack
React
JSON.stringify
<anonymous>
React
new Promise
<anonymous>
React
encodeReply
../src/client/components/router-reducer/reducers/server-action-reducer.ts
fetchServerAction
../src/client/components/router-reducer/reducers/server-action-reducer.ts
state
../src/client/components/router-reducer/router-reducer.ts
state
../src/shared/lib/router/action-queue.ts
action
../src/shared/lib/router/action-queue.ts
runAction
../src/shared/lib/router/action-queue.ts
runRemainingActions
../src/shared/lib/router/action-queue.ts@Kurilian Bobtail