Refactor image upload handling by moving upload directory outside of public folder for better compatibility with Next.js. Update related Docker configurations and scripts to reflect new upload paths. Replace instances of Next.js Image component with CmsImage for consistent image handling across the application.

This commit is contained in:
smhk1376 committed 2026-10-22 12:51:18 +03:30
1 parent 0a57ef2b80
commit 1641edfd01
19 files changed
+162 -39

No files matched your search

+3 -3
View File
@@ -24,9 +24,9 @@
.DS_Store
*.pem
# admin-uploaded images (keep folder via .gitkeep)
/public/uploads/*
!/public/uploads/.gitkeep
# admin-uploaded images (served by GET /uploads/[...path], not public/)
/uploads/
/public/uploads/
# debug
npm-debug.log*
+5 -2
View File
@@ -36,8 +36,11 @@ COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
# Writable dir for admin image uploads (mount a volume in compose for persistence)
RUN mkdir -p ./public/uploads && chown -R nextjs:nodejs ./public/uploads
# Writable dir for admin image uploads (mount a volume in compose for persistence).
# Keep this outside public/: Next standalone does not serve runtime public files.
RUN rm -rf ./public/uploads \
&& mkdir -p ./uploads \
&& chown -R nextjs:nodejs ./uploads
USER nextjs
+5 -2
View File
@@ -18,8 +18,11 @@ COPY --chown=nextjs:nodejs . ./
# Next warns/breaks if a legacy root-level ./static exists alongside ./public
RUN rm -rf ./static
# Writable dir for admin image uploads (mount a volume in compose for persistence)
RUN mkdir -p ./public/uploads && chown -R nextjs:nodejs ./public/uploads
# Writable dir for admin image uploads (mount a volume in compose for persistence).
# Keep this outside public/: Next standalone does not serve runtime public files.
RUN rm -rf ./public/uploads \
&& mkdir -p ./uploads \
&& chown -R nextjs:nodejs ./uploads
USER nextjs
EXPOSE 3000
+2 -2
View File
@@ -13,11 +13,11 @@ services:
- HOSTNAME=0.0.0.0
- NEXT_PUBLIC_SITE_URL=${NEXT_PUBLIC_SITE_URL:-https://edu.mstaut.ir}
- DATABASE_URL=${DATABASE_URL:?Set DATABASE_URL in a protected environment file}
- UPLOAD_DIR=/app/public/uploads
- UPLOAD_DIR=/app/uploads
# Nginx Proxy Manager: edu.mstaut.ir → http://aut-management-faculty:3000
# DB: same Docker network as container `insaight-postgres` (not the public IP).
volumes:
- uploads_data:/app/public/uploads
- uploads_data:/app/uploads
expose:
- "3000"
networks:
View File
Whitespace-only changes.
+4 -4
View File
@@ -44,8 +44,8 @@ docker run --rm --network "$NETWORK" --env-file "$ENV_FILE" \
# Check the database and a minimal page set before switching the public upstream.
CANDIDATE="edu-candidate-${REVISION:0:12}"
docker run -d --name "$CANDIDATE" --network "$NETWORK" --env-file "$ENV_FILE" \
-e UPLOAD_DIR=/app/public/uploads \
-v "$UPLOAD_VOLUME:/app/public/uploads" \
-e UPLOAD_DIR=/app/uploads \
-v "$UPLOAD_VOLUME:/app/uploads" \
"$IMAGE"
cleanup_candidate() { docker rm -f "$CANDIDATE" >/dev/null 2>&1 || true; }
trap cleanup_candidate EXIT
@@ -101,8 +101,8 @@ rollback() {
trap rollback ERR
docker run -d --name "$CONTAINER" --restart unless-stopped \
--network "$NETWORK" --env-file "$ENV_FILE" \
-e UPLOAD_DIR=/app/public/uploads \
-v "$UPLOAD_VOLUME:/app/public/uploads" \
-e UPLOAD_DIR=/app/uploads \
-v "$UPLOAD_VOLUME:/app/uploads" \
-p 127.0.0.1:3000:3000 "$IMAGE"
READY=false
for attempt in $(seq 1 20); do
+3 -5
View File
@@ -149,17 +149,15 @@ async function main() {
}
const sequences = await client.query(`
SELECT sequencename, last_value, is_called
SELECT sequencename, last_value
FROM pg_sequences
WHERE schemaname = 'public'
ORDER BY sequencename
`);
for (const seq of sequences.rows) {
const called = seq.is_called === true;
if (seq.last_value == null) continue;
const seqName = String(seq.sequencename).replaceAll("'", "''");
lines.push(
`SELECT setval('${seqName}', ${Number(seq.last_value)}, ${called});`,
);
lines.push(`SELECT setval('${seqName}', ${Number(seq.last_value)}, true);`);
}
lines.push("", "COMMIT;", "");
+2 -2
View File
@@ -1,6 +1,6 @@
import type { Metadata } from "next";
import Image from "next/image";
import { getTranslations } from "next-intl/server";
import { CmsImage } from "@/components/atoms/CmsImage";
import { Container } from "@/components/atoms/Container";
import { Heading } from "@/components/atoms/Heading";
import { Section } from "@/components/atoms/Section";
@@ -41,7 +41,7 @@ export default async function AlumniPage() {
className="scroll-mt-24"
>
<div className="relative aspect-[16/10] bg-muted">
<Image
<CmsImage
src={story.imageUrl}
alt={story.name}
fill
+2 -2
View File
@@ -1,6 +1,6 @@
import type { Metadata } from "next";
import Image from "next/image";
import { notFound } from "next/navigation";
import { CmsImage } from "@/components/atoms/CmsImage";
import { Container } from "@/components/atoms/Container";
import { Section } from "@/components/atoms/Section";
import { TextLink } from "@/components/atoms/TextLink";
@@ -56,7 +56,7 @@ export default async function InsightDetailPage({ params }: Props) {
<Section tone="subtle">
<Container narrow>
<div className="relative mb-10 aspect-[16/9] overflow-hidden rounded-2xl bg-muted ring-1 ring-foreground/10">
<Image
<CmsImage
src={article.imageUrl}
alt={article.title}
fill
+60
View File
@@ -0,0 +1,60 @@
import { readFile, stat } from "node:fs/promises";
import path from "node:path";
import { NextResponse } from "next/server";
import {
mimeForUploadExt,
resolveStoredUploadPath,
} from "@/lib/uploads/image";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
type RouteParams = { params: Promise<{ path: string[] }> };
async function lookupUpload(segments: string[]) {
const absolutePath = resolveStoredUploadPath(segments);
if (!absolutePath) return null;
try {
const info = await stat(absolutePath);
if (!info.isFile()) return null;
const mime = mimeForUploadExt(path.extname(absolutePath));
if (!mime) return null;
return { absolutePath, info, mime };
} catch {
return null;
}
}
function headersFor(file: { info: { size: number }; mime: string }) {
return {
"Content-Type": file.mime,
"Content-Length": String(file.info.size),
"Cache-Control": "public, max-age=31536000, immutable",
};
}
export async function GET(_request: Request, { params }: RouteParams) {
const { path: segments } = await params;
const file = await lookupUpload(segments);
if (!file) {
return new NextResponse("Not found", { status: 404 });
}
const buffer = await readFile(file.absolutePath);
return new NextResponse(buffer, {
status: 200,
headers: headersFor(file),
});
}
export async function HEAD(_request: Request, { params }: RouteParams) {
const { path: segments } = await params;
const file = await lookupUpload(segments);
if (!file) {
return new NextResponse(null, { status: 404 });
}
return new NextResponse(null, {
status: 200,
headers: headersFor(file),
});
}
+14
View File
@@ -0,0 +1,14 @@
import Image, { type ImageProps } from "next/image";
import { isRuntimeUploadSrc } from "@/lib/uploads/types";
/**
* next/image optimizer reads from `public/` at build time. Runtime uploads
* live outside that tree, so skip optimization for `/uploads/...`.
*/
export function CmsImage({ src, unoptimized, ...props }: ImageProps) {
const skipOptimize =
unoptimized ??
(typeof src === "string" && isRuntimeUploadSrc(src));
return <Image src={src} unoptimized={skipOptimize} {...props} />;
}
+4 -4
View File
@@ -1,5 +1,5 @@
import Image from "next/image";
import Link from "next/link";
import { CmsImage } from "@/components/atoms/CmsImage";
import { ArrowUpLeft, MapPin, Wifi } from "lucide-react";
import {
Card,
@@ -65,7 +65,7 @@ export function ArticleCard({
return (
<article className="group grid overflow-hidden border-b border-border py-7 first:pt-0 last:border-b-0 sm:grid-cols-[14rem_1fr] sm:gap-8 lg:grid-cols-[19rem_1fr] lg:py-9">
<Link href={href} className="relative aspect-[16/10] overflow-hidden rounded-xl bg-muted sm:aspect-auto sm:min-h-44">
<Image src={imageUrl} alt={title} fill placeholder="blur" blurDataURL={blurDataURL} className="object-cover transition-transform duration-500 group-hover:scale-[1.025]" sizes="(max-width:640px) 100vw, 304px" />
<CmsImage src={imageUrl} alt={title} fill placeholder="blur" blurDataURL={blurDataURL} className="object-cover transition-transform duration-500 group-hover:scale-[1.025]" sizes="(max-width:640px) 100vw, 304px" />
</Link>
<div className="flex min-w-0 flex-col justify-center pt-5 sm:pt-0">
<p className="text-xs font-bold text-accent">{category}</p>
@@ -101,7 +101,7 @@ export function ArticleCard({
featured ? "aspect-[16/10]" : "aspect-[4/3]",
)}
>
<Image
<CmsImage
src={imageUrl}
alt={title}
fill
@@ -236,7 +236,7 @@ export function IntersectionCard({
className="group relative block min-h-[16rem] overflow-hidden rounded-2xl bg-primary shadow-sm sm:min-h-[18rem]"
>
<div className="absolute inset-0 overflow-hidden">
<Image
<CmsImage
src={imageUrl}
alt={title}
fill
@@ -1,4 +1,4 @@
import Image from "next/image";
import { CmsImage } from "@/components/atoms/CmsImage";
/** Card media: banner image when set; otherwise course title on themed surface. */
export function CourseCardBanner({
@@ -13,7 +13,7 @@ export function CourseCardBanner({
return (
<div className="pointer-events-none relative aspect-video overflow-hidden bg-primary-foreground/10">
{hasBanner ? (
<Image
<CmsImage
src={bannerUrl!}
alt=""
fill
@@ -1,4 +1,4 @@
import Image from "next/image";
import { CmsImage } from "@/components/atoms/CmsImage";
import { cn } from "@/lib/utils";
/**
@@ -28,7 +28,7 @@ export function CourseMediaFigure({
className,
)}
>
<Image
<CmsImage
src={src}
alt={alt}
width={width}
@@ -1,5 +1,5 @@
import Image from "next/image";
import { ExternalLink, GraduationCap } from "lucide-react";
import { CmsImage } from "@/components/atoms/CmsImage";
import { Heading } from "@/components/atoms/Heading";
import { SurfaceCard } from "@/components/molecules/SurfaceCard";
import { buttonVariants } from "@/components/ui/button";
@@ -25,7 +25,7 @@ export function FacultyMemberCard({ member }: { member: FacultyMember }) {
<SurfaceCard className="group flex h-full flex-col rounded-2xl">
<div className="relative mb-5 aspect-[4/3] overflow-hidden rounded-xl bg-muted">
{photo ? (
<Image
<CmsImage
src={member.imageUrl}
alt={member.name}
fill
+2 -2
View File
@@ -1,5 +1,5 @@
import type { ReactNode } from "react";
import Image from "next/image";
import { CmsImage } from "@/components/atoms/CmsImage";
import { Container } from "@/components/atoms/Container";
import { Heading } from "@/components/atoms/Heading";
import { MetamorphField } from "@/components/atoms/MetamorphField";
@@ -35,7 +35,7 @@ export function PageHero({
: "py-16 sm:py-24",
)}
>
<Image
<CmsImage
src={imageUrl ?? "/brand/neural-learning-wave.webp"}
alt=""
fill
@@ -1,9 +1,9 @@
"use client";
import { useRef, useState } from "react";
import Image from "next/image";
import { ImageIcon, Loader2, Trash2, Upload } from "lucide-react";
import { Button } from "@/components/ui/button";
import { CmsImage } from "@/components/atoms/CmsImage";
import { cn } from "@/lib/utils";
import type { UploadFolder } from "@/lib/uploads/types";
@@ -75,11 +75,10 @@ export function ImageUploadField({
{value ? (
<div className="overflow-hidden rounded-xl border border-border bg-muted/40">
<div className="relative aspect-[16/9] w-full max-w-md bg-muted">
<Image
<CmsImage
src={value}
alt="پیش نمایش تصویر"
fill
unoptimized
className="object-cover"
sizes="(max-width: 768px) 100vw, 28rem"
/>
+43 -2
View File
@@ -17,12 +17,53 @@ const MIME_TO_EXT = new Map<string, string>([
["image/gif", "gif"],
]);
/** Disk root for uploaded images. Override with UPLOAD_DIR for Docker volumes. */
const EXT_TO_MIME = new Map<string, string>([
[".jpg", "image/jpeg"],
[".jpeg", "image/jpeg"],
[".png", "image/png"],
[".webp", "image/webp"],
[".gif", "image/gif"],
]);
/** UUID filenames written by saveUploadedImage. */
const STORED_FILENAME = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.(jpg|jpeg|png|webp|gif)$/;
/**
* Disk root for uploaded images.
* Keep this *outside* `public/` in production: Next standalone does not
* reliably serve files added to `public/` after the image is built.
* Override with UPLOAD_DIR for Docker volumes.
*/
export function getUploadsRoot(): string {
if (process.env.UPLOAD_DIR) {
return path.resolve(process.env.UPLOAD_DIR);
}
return path.join(process.cwd(), "public", "uploads");
return path.join(process.cwd(), "uploads");
}
export function mimeForUploadExt(ext: string): string | undefined {
return EXT_TO_MIME.get(ext.toLowerCase());
}
/**
* Resolve `folder/uuid.ext` to an absolute path under the uploads root.
* Returns null for anything that is not a stored upload (traversal, extra
* segments, unknown folder, or unexpected filename).
*/
export function resolveStoredUploadPath(segments: string[]): string | null {
if (segments.length !== 2) return null;
const [folder, filename] = segments;
if (!folder || !filename) return null;
if (!isUploadFolder(folder)) return null;
if (!STORED_FILENAME.test(filename)) return null;
const root = getUploadsRoot();
const absolutePath = path.resolve(root, folder, filename);
const relative = path.relative(root, absolutePath);
if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) {
return null;
}
return absolutePath;
}
export function publicUrlFor(relativePath: string): string {
+5
View File
@@ -12,3 +12,8 @@ export type UploadFolder = (typeof UPLOAD_FOLDERS)[number];
export function isUploadFolder(value: string): value is UploadFolder {
return (UPLOAD_FOLDERS as readonly string[]).includes(value);
}
/** True for images written at runtime (`/uploads/{folder}/{uuid}.ext`). */
export function isRuntimeUploadSrc(src: string): boolean {
return src.startsWith("/uploads/");
}