Now.js Framework Documentation

Now.js Framework Documentation

RedirectManager

TH 04 Sep 2026 01:40

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;
}

Intended Route

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

storeIntendedRoute()

บันทึก current URL

RedirectManager.storeIntendedRoute();

getIntendedRoute()

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

Returns: string|null

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

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

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