Now.js Framework Documentation

Now.js Framework Documentation

RedirectManager

TH 13 Nov 2026 06:18

RedirectManager

ภาพรวม

RedirectManager คือระบบจัดการ redirects ใน Now.js Framework รองรับ auth redirects, intended URL storage และ configurable redirect types

ใช้เมื่อ:

  • ต้องการ redirect หลัง login
  • ต้องการ redirect สำหรับ unauthorized access
  • ต้องการ store intended URL
  • ต้องการ guest-only routes

ทำไมต้องใช้:

  • ✅ Pre-defined redirect types
  • ✅ Intended route storage
  • ✅ Query/hash preservation
  • ✅ Notification integration
  • ✅ SPA และ full-page redirect support

การใช้งานพื้นฐาน

Redirect Types

// Auth required redirect
RedirectManager.requireAuth();

// After login
RedirectManager.afterLogin();

// After logout
RedirectManager.afterLogout();

// Forbidden (403)
RedirectManager.forbidden();

// Guest only (redirect logged-in users)
RedirectManager.guestOnly();

Custom Redirect

RedirectManager.redirect('auth_required', {
  target: '/custom-login',
  message: 'กรุณาเข้าสู่ระบบ'
});

Redirect Types

Type Default Target Description
auth_required /login User ต้อง login
forbidden /403 ไม่มีสิทธิ์
after_login / หรือ intended หลัง login สำเร็จ
after_logout /login หลัง logout
guest_only / เฉพาะ guest
maintenance /maintenance ระบบปิดปรับปรุง
not_found /404 หน้าไม่พบ

Default Configurations

RedirectManager.defaults = {
  auth_required: {
    target: '/login',
    preserveQuery: true,      // Keep query string
    preserveHash: true,       // Keep hash
    storeIntended: true,      // Store current URL
    message: 'Please login to continue',
    showNotification: true
  },
  after_login: {
    target: '/',
    useIntended: true,        // Go to stored URL
    clearIntended: true,      // Clear after use
    showNotification: false
  },
  // ... other types
};

API อ้างอิง

RedirectManager.redirect(type, options)

ทำ redirect

Parameter Type Description
type string Redirect type
options.target string Override target URL
options.message string Override message
options.params object URL parameters
RedirectManager.redirect('auth_required', {
  target: '/login',
  params: { returnTo: '/checkout' },
  message: 'กรุณาเข้าสู่ระบบเพื่อทำการสั่งซื้อ'
});

RedirectManager.requireAuth(options?)

Redirect ไป login

// Route guard
if (!isAuthenticated) {
  RedirectManager.requireAuth();
  return;
}

RedirectManager.afterLogin(options?)

Redirect หลัง login สำเร็จ

// หลัง login สำเร็จ
async function handleLogin(credentials) {
  await AuthManager.login(credentials);
  RedirectManager.afterLogin();
}

FormManager เรียกให้เองทุกครั้งที่ฟอร์มชื่อ data-form="login" submit สำเร็จ ซึ่งเป็นชื่อที่ถูกสงวนไว้
ดู ชื่อฟอร์มที่ถูกสงวน ฟอร์มแบบนี้จึงไม่สนใจ
data-success-redirect และ data-redirect ปลายทางมาจาก data-redirect-after-login
ถ้าไม่มีก็ใช้ intended route ที่เก็บไว้ ถัดไปคือ RouterManager.config.auth.redirects.afterLogin
และสุดท้ายคือ /

RedirectManager.afterLogout(options?)

Redirect หลัง logout

async function handleLogout() {
  await AuthManager.logout();
  RedirectManager.afterLogout();
}

RedirectManager.forbidden(options?)

Redirect ไป 403

RedirectManager.guestOnly(options?)

Redirect logged-in users ออก

// Login page guard
if (isAuthenticated) {
  RedirectManager.guestOnly();
  return;
}

ปลายทางและ base ของ router

ปลายทางของทุกชนิดเป็น route path (/login, /403) ที่นับจาก base ของ router
ค่าที่ตั้งใน router.auth.redirects ใช้แทนค่าเริ่มต้น: unauthenticated (หรือ unauthorized)
สำหรับ auth_required, forbidden, afterLogin สำหรับ after_login/guest_only และ afterLogout
เมื่อ router ทำงานอยู่ (SPA) การ redirect ผ่าน RouterManager.navigate() เมื่อ router ปิดอยู่
จะโหลดหน้าใหม่ทั้งหน้าที่ resolveUrl(target) ซึ่งเติม base ให้ เช่น base /app + /login → /app/login
(รวมทั้ง performFallbackRedirect() เมื่อ redirect ล้มเหลว)

RedirectManager.go(target, options?)

ไปที่ route path ผ่าน router เมื่อ router ทำงาน ไม่เช่นนั้นโหลดหน้าใหม่ที่ resolveUrl(target)

Parameter Type Description
target string route path เช่น / หรือ /403?message=x (ขึ้นต้นด้วย base มาแล้วก็ได้)
options.replace boolean แทนที่รายการประวัติปัจจุบัน
options.useRouter boolean false = บังคับโหลดหน้าใหม่

คืนค่า: Promise<{method: 'router'|'location', success: boolean}>

RedirectManager.resolveUrl(target)

แปลง route path เป็น URL สำหรับแถบที่อยู่: path ที่ขึ้นต้นด้วย / ได้ base นำหน้า
ถ้ายังไม่ขึ้นต้นด้วย base · URL เต็มและ path แบบ relative คืนตามเดิม

// base = '/app'
RedirectManager.resolveUrl('/login');      // '/app/login'
RedirectManager.resolveUrl('/app/users');  // '/app/users'
RedirectManager.resolveUrl('https://example.com/x'); // ไม่เปลี่ยน

RedirectManager.redirectForStatus(status, options?)

ออกจากหน้าหลังคำขอข้อมูลได้คำตอบ 401 หรือ 403: 401 ไปหน้า login (เก็บหน้าปัจจุบันเป็น
intended route) 403 ไปหน้าไม่มีสิทธิ์ พร้อมข้อความจาก server เป็น ?message= ทั้งสองแบบไม่แสดง
notification · FormManager (data-load-api), ApiComponent และ TableManager (data-source) ใช้เมธอดนี้

Parameter Type Description
status number สถานะ HTTP
options.message string ข้อความจาก server (ใช้กับ 403)

คืนค่า: true เมื่อสถานะเป็น 401/403 และเริ่ม redirect แล้ว

const res = await http.get('api/report');
if (RedirectManager.redirectForStatus(res.status, {message: res.data?.message})) return;

Intended Route

จัดเก็บ route ที่ user ตั้งใจจะไป:

storeIntendedRoute()

บันทึก current URL

RedirectManager.storeIntendedRoute();

getIntendedRoute()

รับ URL ที่เก็บไว้

Returns: string|null

const intended = RedirectManager.getIntendedRoute();
// '/dashboard/settings'

isSafeIntendedPath(path)

path ที่เก็บไว้ redirect ไปหลังล็อกอินได้หรือไม่: ต้องเป็น path ในเว็บนี้ที่ resolve (แบบเดียวกับเบราว์เซอร์) แล้วยังอยู่ origin ของหน้านี้ และไม่ใช่หน้า auth เช่น /login · backslash หรืออักขระควบคุม (tab, ขึ้นบรรทัด) ถูกปฏิเสธทันที — /\evil.example/x และ /<tab>/evil.example จะพาไป host อื่น · path ที่ resolve แล้วขึ้นต้นด้วย // ก็ถูกปฏิเสธ (/..//evil.example อยู่ในเว็บนี้แต่ไปจบที่ path //evil.example ซึ่งโค้ดที่ใช้ location.pathname เป็น URL จะพาไปเว็บอื่น)

RedirectManager.isSafeIntendedPath('/orders?id=1');      // true
RedirectManager.isSafeIntendedPath('//evil.example/');   // false
RedirectManager.isSafeIntendedPath('/\\evil.example/x'); // false
RedirectManager.isSafeIntendedPath('/..//evil.example');  // false

Returns: boolean

clearIntendedRoute()

ล้าง stored URL

RedirectManager.clearIntendedRoute();

เหตุการณ์

Event เมื่อเกิด Detail
auth:redirect ก่อนพาผู้ใช้ไปปลายทาง {type, config, target, from, timestamp}
EventManager.on('auth:redirect', ({type, target, from}) => {
  console.log('Redirecting', from, '→', target, '(', type, ')');
});

Integration Examples

Route Guard

// middleware/auth.js
function requireAuth(to, from, next) {
  if (!AuthManager.isAuthenticated()) {
    RedirectManager.redirect('auth_required', {
      storeIntended: true
    });
    return;
  }
  next();
}

Login Page

// pages/login.js
async function handleLoginSubmit(data) {
  try {
    await AuthManager.login(data);

    // Redirect to intended or dashboard
    RedirectManager.afterLogin({
      fallbackTarget: '/dashboard'
    });
  } catch (error) {
    showError(error.message);
  }
}

Protected API Call

async function fetchUserData() {
  try {
    return await ApiService.get('/api/user');
  } catch (error) {
    if (error.status === 401) {
      RedirectManager.requireAuth({
        message: 'Session หมดอายุ กรุณาเข้าสู่ระบบใหม่'
      });
    }
    throw error;
  }
}

Multi-Role Redirect

function redirectByRole(user) {
  const roleTargets = {
    admin: '/admin/dashboard',
    manager: '/manager/reports',
    user: '/user/home'
  };

  RedirectManager.redirect('after_login', {
    target: roleTargets[user.role] || '/home'
  });
}

ข้อควรระวัง

⚠️ 1. Intended Route ใน SPA

// ❌ Intended route หายหลัง refresh
// (ใช้ sessionStorage แทน localStorage)

// ✅ Framework จัดการให้อัตโนมัติ
RedirectManager.requireAuth();  // stores in sessionStorage

⚠️ 2. Query String Handling

// ❌ Query หาย
redirect('/login');

// ✅ Preserve query
RedirectManager.redirect('auth_required', {
  preserveQuery: true
});
// /login?returnTo=/current/page

เอกสารที่เกี่ยวข้อง